简体   繁体   English

通过refs设置为变量来反应查找DOM节点?

[英]React find DOM node by refs set to variable?

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: ''
  });
},
var Value = React.findDOMNode(this.refs.refID).value;

finds the DOM node for the component with the ref "refID" . 找到具有ref "refID"的组件的DOM节点。 If you want to find the DOM node for the component with the ref refID (the variable), you need 如果要查找具有ref refID (变量)的组件的DOM节点,则需要

var Value = ReactDOM.findDOMNode(this.refs[refID]).value;

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

I am getting a "Cannot read property 'value' of null" error. 我得到一个“无法读取属性'值的'null”错误。

Two possible cases: 两种可能的情况:

  • the id is wrong. id错了。 Review further code or log to double check the ID is what you think it is 查看更多代码或log以仔细检查ID是否是您认为的
  • Called to early: Are you sure that componentDidMount has been called? 早叫:你确定已经调用了componentDidMount吗?

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM