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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-28 12:38:21  来源:igfitidea点击:

Iterate over all refs values in component

javascriptreactjsreact-jsx

提问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.refsis 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.

回答by Deano

Using lodashyou can iterate over this.refsand create simple object.

使用lodash你可以迭代this.refs并创建简单的对象。

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