【问题标题】:React ref not working Invariant Violation: addComponentAsRefToReact ref 不工作不变违规:addComponentAsRefTo
【发布时间】:2016-11-13 21:55:00
【问题描述】:

我在将 ref 添加到 React 组件时遇到问题。以下是错误信息。

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 可以有 refs

这是我不熟悉 react 的最可能原因。我有一个容器被渲染,然后一个选择元素被渲染到容器中。

代码

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

好像也没有重复的包?关于这里可能发生什么的任何想法?

【问题讨论】:

    标签: javascript html reactjs npm


    【解决方案1】:

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

    好:

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

    不好:

     <input ref="textInput" />
    

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

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

    “如果你之前使用过 React,你可能熟悉一个旧的 API,其中 ref 属性是一个字符串,比如“textInput”,并且 DOM 节点作为 this.refs.textInput 访问。我们不建议这样做,因为字符串引用存在一些问题,被认为是遗留问题,并且可能会在未来的某个版本中被删除。如果您当前使用 this.refs.textInput 访问引用,我们建议改为使用回调模式。"

    【讨论】:

    • 请不要对多个问题发布相同的答案。发布一个好的答案,然后投票/标记以关闭其他问题作为重复问题。如果问题不是重复的,调整您对该问题的回答。
    猜你喜欢
    • 2015-07-18
    • 2015-08-07
    • 2016-03-02
    • 1970-01-01
    • 2018-07-07
    • 2017-02-27
    • 1970-01-01
    • 1970-01-01
    • 2016-06-10
    相关资源
    最近更新 更多