【发布时间】: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