最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - React find DOM node by refs set to variable? - Stack Overflow

programmeradmin2浏览0评论

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

I am getting a "Cannot read property 'value' of null" error.

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: ''
  });
},

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

I am getting a "Cannot read property 'value' of null" error.

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: ''
  });
},
Share Improve this question asked Oct 14, 2015 at 1:11 Mark AndersonMark Anderson 6631 gold badge8 silver badges14 bronze badges
Add a comment  | 

3 Answers 3

Reset to default 12
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

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)

I am getting a "Cannot read property 'value' of null" error.

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?
发布评论

评论列表(0)

  1. 暂无评论