[英]Get props from child form component , ReactJS
I am new to React
. 我是
React
新手。
I am writing a component ArrayInput
that contains multiple(based on state) input box. 我正在写一个组件
ArrayInput
,其中包含多个(基于状态)输入框。
And ArrayInput
need to handle each input box's onChange event. 而且
ArrayInput
需要处理每个输入框的onChange事件。
I hope to get some specific props/attribute (in this case , "index") on these dramatically generated input box 我希望在这些生成的输入框上获得一些特定的道具/属性(在本例中为“索引”)
I search for many posts and docs but can't find the correct way. 我搜索许多帖子和文档,但找不到正确的方法。
I know I can use this.ref[inputBoxRef]
(react 14+) to get the actual DOM node , but find it has no "attribute" or "data" when using $(domnode).attr('index')
or $(domnode).data('index')
. 我知道我可以使用
this.ref[inputBoxRef]
(反应14+)来获取实际的DOM节点,但是在使用$(domnode).attr('index')
或$(domnode).data('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>
)
}
});
You can always use event.target
. 您可以始终使用
event.target
。 try event.target.index
. 尝试
event.target.index
。
Your <input>
(with lowercase) is a standard HTML component. 您的
<input>
(小写)是标准的HTML组件。
Probably best to try and avoid to put custom attributes on these components in react. 最好避免尝试将自定义属性放在这些组件上以作出反应。
Because in effect you are then unnecessarily poluting your DOM with data that could and should be passed within react itself. 因为实际上,您不必要地使用可以并且应该在内部传递的数据污染DOM。 And it is a long trip from react to DOM, to react reading the DOM again to get the data.
从反应到DOM,再做出反应以再次读取DOM以获取数据,这是一个漫长的旅程。
If you want to know the index
variable inside handleChange, bind it to the call to handler, like: 如果您想知道handleChange内部的
index
变量,请将其绑定到对处理程序的调用,例如:
onChange={self.handleChange.bind(self,i)}
and if you change you handler definition to: 并且如果您将处理程序定义更改为:
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
To get the access the item's value (or any other DOM attribute), as well as the index. 为了获得访问权限,需要使用项目的值(或任何其他DOM属性)以及索引。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.