React ref not working Invariant Violation: addComponentAsRefTo

时间:2016-07-11 20:25:18

标签: javascript html reactjs npm

I am having an issue with adding a ref to a react component. Below is the error message.

invariant.js:39Uncaught Invariant Violation: addComponentAsRefTo(...): Only a ReactOwner can have refs. You might be adding a ref to a component that was not created inside a component's `render` method, or you have multiple copies of React loaded

Research shows to probable causes for this, and neither seem to be the issue.

Only a ReactOwner can have refs

This is the most likely cause do to my unfamiliarity with react. I have a container being rendered, and then a select element being rendered into the container.

Code

var React = require('react');

var first_container = React.createClass({
    render: function() {
        return (
            <div id='first-container' className='jumbotron'>
               <div className='row'>
                  <button type='button' className='btn btn-primary'>Submit Query</button>
               </div>
        </div>
         );
     }
});


var product_selections = React.createClass({
   handleChange: function() {
      console.log("hello");
   },
   componentDidMount: function (){
      $(this.refs['product-select']).select2({
         change: this.handleChange
      });
   },
     render: function() {
        return (
            <div className='row'>
               <br/>
               <label htmlFor='product-dropdown'>
                  Product
                  <br/>
                  <select ref='product-select' className='js-example-basic-multiple js-states form-control' id='product-dropdown' multiple='multiple'>
                  </select>
               </label>
            </div>
        );
    }
});

You are trying to add a ref to an element that is being created outside of a component's render() function.

The ref is defined inside the render function, so it doesn't seem that that is the issue. Could it be that it's because this component is being added to another component?

Multiple Copies of React

npm ls | grep react

├─┬ react@15.2.1
├── react-addons@0.9.0
├── react-bootstrap@0.29.5 extraneous
├── react-dom@15.2.1
├─┬ reactify@0.15.2
│ ├─┬ react-tools@0.12.2

There does not seem to be a duplicate package either? Any ideas on what could be happening here?

1 个答案:

答案 0 :(得分:0)

我有一个类似的问题,并且能够通过不使用字符串引用来解决它。

好:

 <input ref={(input) => { this.textInput = input }} />

为:

 <input ref="textInput" />

在这里查看文档: https://facebook.github.io/react/docs/refs-and-the-dom.html

他们实际上说不要这样做:

&#34;如果你以前使用过React,你可能熟悉一个旧的API,其中ref属性是一个字符串,例如&#34; textInput&#34;,并且DOM节点作为this.refs访问.textInput。我们建议不要使用它,因为字符串引用有一些问题,被认为是遗留问题,很可能会在未来的某个版本中删除。如果您当前正在使用this.refs.textInput访问引用,我们建议使用回调模式。&#34;