遍历组件中的所有 refs 值
Iterate over all refs values in component
我正在尝试访问我的组件中的所有 ref 值并对它们做一些事情(例如,创建有效负载以发送到服务器)
我试图做一个简单的 for..in 循环,而不是在每个引用上使用 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>
)
}
});
这是我正在使用的 jsfiddle。
我觉得,这可能不是一个好主意,但我不知道如何处理这个 atm。
有人帮忙吗?
这是因为this.refs
是一个对象,你需要获取值,而不是键:
getAllRefsValues: function() {
for (var ref in this.refs) {
console.log(this.refs[ref]);
console.log(this.refs[ref].getDOMNode());
}
}
无论如何,根据我的经验,最好使用 Controlled Components 而不是 refs
。
使用 lodash 您可以遍历 this.refs
并创建简单的对象。
let data = _.mapValues(this.refs, function(ref) { return ref.value });
我正在尝试访问我的组件中的所有 ref 值并对它们做一些事情(例如,创建有效负载以发送到服务器)
我试图做一个简单的 for..in 循环,而不是在每个引用上使用 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>
)
}
});
这是我正在使用的 jsfiddle。
我觉得,这可能不是一个好主意,但我不知道如何处理这个 atm。
有人帮忙吗?
这是因为this.refs
是一个对象,你需要获取值,而不是键:
getAllRefsValues: function() {
for (var ref in this.refs) {
console.log(this.refs[ref]);
console.log(this.refs[ref].getDOMNode());
}
}
无论如何,根据我的经验,最好使用 Controlled Components 而不是 refs
。
使用 lodash 您可以遍历 this.refs
并创建简单的对象。
let data = _.mapValues(this.refs, function(ref) { return ref.value });