Javascript React 通过设置为变量的 refs 查找 DOM 节点?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/33115054/
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
React find DOM node by refs set to variable?
提问by Mark Anderson
I am dynamically creating multiple text inputs (with dynamically created refs) along side the text that I want updated with the input.
我正在动态创建多个文本输入(使用动态创建的参考)以及我想要使用输入更新的文本。
I am trying to get the value of the input by setting the ref to a variable and finding the DOM node with React.findDOMNode(this.refs.Variable).value
我试图通过将 ref 设置为变量并使用 React.findDOMNode(this.refs.Variable).value 查找 DOM 节点来获取输入的值
I am getting a "Cannot read property 'value' of null" error.
我收到“无法读取 null 的属性‘值’”错误。
How can I achieve this?
我怎样才能做到这一点?
This is what the function looks like:
这是函数的样子:
resetUnit: function(e){
var refID = e.target.id;
var ID = refID.split("-")[0];
var Value = React.findDOMNode(this.refs.refID).value;
NodesCollection.update({_id: ID},{$set: { materialUnit : Value}});
this.setState({
edit: ''
});
},
回答by Michelle Tilley
var Value = React.findDOMNode(this.refs.refID).value;
finds the DOM node for the component with the ref "refID"
. If you want to find the DOM node for the component with the ref refID
(the variable), you need
找到具有 ref 的组件的 DOM 节点"refID"
。如果要使用 ref refID
(变量)查找组件的 DOM 节点,则需要
var Value = ReactDOM.findDOMNode(this.refs[refID]).value;
回答by lakesare
I had to do
我必须做
import ReactDOM from 'react-dom';
ReactDOM.findDOMNode(this.refs.hi);
in React 15.2.1 (https://facebook.github.io/react/docs/top-level-api.html#reactdom.finddomnode)
在 React 15.2.1 ( https://facebook.github.io/react/docs/top-level-api.html#reactdom.finddomnode)
回答by basarat
I am getting a "Cannot read property 'value' of null" error.
我收到“无法读取 null 的属性‘值’”错误。
Two possible cases:
两种可能的情况:
- the id is wrong. Review further code or
log
to double check the ID is what you think it is - Called to early: Are you sure that
componentDidMount
has been called?
- id错了 查看更多代码或
log
仔细检查 ID 是您认为的内容 - 提前打电话:你确定
componentDidMount
已经打电话了吗?