从子窗体组件ReactJS中获取道具

Get props from child form component , ReactJS

本文关键字:获取 ReactJS 窗体 组件      更新时间:2023-09-26

我是React的新手。

我正在编写一个组件ArrayInput,它包含多个(基于状态)输入框。

ArrayInput需要处理每个输入框的onChange事件。

我希望在这些戏剧性地生成的输入框上获得一些特定的道具/属性(在本例中为"索引")

我搜索了很多帖子和文档,但找不到正确的方法。

我知道我可以使用this.ref[inputBoxRef](react 14+)来获得实际的DOM节点,但在使用$(domnode).attr('index')$(domnode).data('index')时发现它没有"属性"或"数据"。

    window.ArrayInput = React.createClass({
            ......other methods
            handleChange:function(ref,event){
                var domInputBox = this.refs[ref];
                //trying to get the index attribute of this input
             }
            render:function(){
                var self = this;
                return (
                    <div className="input-wrapper"  >                               
                        <label>
                            <div>{this.props.label}</div>
                            {
                                this.state.value.map(function(e,i){
                                    return  (                           
                                        <input type="text"
                                            ref={"arrayBox"+i}
                                            key={"arrayBox"+i}
                                            index={i} //custom attribute
                                            value={e}
                                            onChange={self.handleChange.bind(self,"arrayBox"+i)}
                                        />
                                    )
                                })
                            }
                        </label>
                    </div>
                )
            }
    });

您可以始终使用event.target。尝试event.target.index

您的<input>(小写)是一个标准的HTML组件。

可能最好尽量避免将自定义属性放在react中的这些组件上
因为实际上,您不必要地使用可以并且应该在react本身中传递的数据来推断DOM。从react到DOM,再读取DOM以获取数据,这是一个漫长的过程。

如果您想知道handleChange中的index变量,请将其绑定到对handler的调用,如:

onChange={self.handleChange.bind(self,i)}

如果您将处理程序定义更改为:

handleChange:function(element,i){
  console.log(element.value);    // outputs value of element that changed
  console.log(i);                // outputs the index of the element that changed

为了获得访问项的值(或任何其他DOM属性)以及索引。