繁体   English   中英

React ref无法正常运行:违反了addComponentAsRefTo

[英]React ref not working Invariant Violation: addComponentAsRefTo

我在向ref组件添加引用时遇到问题。 下面是错误消息。

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

研究表明可能的原因,似乎都不是问题所在。

只有ReactOwner可以具有引用

这是我不熟悉反应的最可能原因。 我正在渲染一个容器,然后将一个select元素渲染到了容器中。

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>
        );
    }
});

您正在尝试向在组件的render()函数外部创建的元素添加ref。

ref是在render函数中定义的,因此似乎并不是问题所在。 可能是因为此组件被添加到另一个组件了吗?

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

似乎也没有重复的包裹吗? 关于这里可能发生什么的任何想法?

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

好:

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

坏:

 <input ref="textInput" />

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

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

“如果您以前使用过React,您可能会熟悉一个较旧的API,其中ref属性是一个字符串,例如“ textInput”,并且可以通过this.refs.textInput访问DOM节点。我们建议不要这样做,因为字符串ref具有有些问题被认为是遗留问题,并且可能会在将来的发行版中删除。如果您当前正在使用this.refs.textInput访问ref,我们建议改用回调模式。”

暂无
暂无

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

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