Iterate over all refs values in component

我的梦境 提交于 2020-01-24 05:54:06

问题


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)

I was trying to do a simple for..in loop and than use getDOMNode().value on every ref but it doesn`t work.

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 jsfiddle I am working with.

I have a feeling that, this might not be a good idea to do, but I have no idea how to approach this atm.

Anyone help ?


回答1:


This is because this.refs is an object, you need to get the values, not the keys:

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 Components over refs.




回答2:


Using lodash you can iterate over this.refs and create simple object.

let data = _.mapValues(this.refs, function(ref) { return ref.value });


来源:https://stackoverflow.com/questions/30734315/iterate-over-all-refs-values-in-component

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!