javascript 遍历组件中的所有 refs 值
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/30734315/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Iterate over all refs values in component
提问by Micha? Lach
I am trying to access all ref values in my component and do something with them (for example, create payload to send to a server)
我正在尝试访问组件中的所有 ref 值并对其进行处理(例如,创建要发送到服务器的有效负载)
I was trying to do a simple for..in loop and than use getDOMNode().value on every ref but it doesn`t work.
我试图做一个简单的 for..in 循环,而不是在每个 ref 上使用 getDOMNode().value 但它不起作用。
var Hello = React.createClass({
getAllRefsValues: function() {
for(ref in this.refs) {
console.log(ref);
// ref.getDOMNode().value doesnt work here
}
},
render: function() {
return (
<div>
<button onClick={this.getAllRefsValues}>Get all props values</button>
<input type="text" ref="test1"/>
<input type="text" ref="test2"/>
<input type="text" ref="test3"/>
</div>
)
}
});
Here is jsfiddleI am working with.
这是我正在使用的jsfiddle。
I have a feeling that, this might not be a good idea to do, but I have no idea how to approach this atm.
我有一种感觉,这可能不是一个好主意,但我不知道如何处理这个 atm。
Anyone help ?
有人帮忙吗?
回答by gcedo
This is because this.refs
is an object, you need to get the values, not the keys:
这是因为this.refs
是一个对象,您需要获取值,而不是键:
getAllRefsValues: function() {
for (var ref in this.refs) {
console.log(this.refs[ref]);
console.log(this.refs[ref].getDOMNode());
}
}
In my experience anyway, it is better to use Controlled Componentsover refs
.
无论如何,根据我的经验,最好使用受控组件而不是refs
.