2016-07-11 14 views
2

反応成分にrefを追加する際に問題があります。以下はエラーメッセージです。反応参照が機能しない不変の違反:addComponentAsRefTo

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これが最も可能性の高い原因は反応すると私の不慣れに行うであることができます。私は、コンテナをレンダリングしてから、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は、render関数内で定義されているため、問題ではないようです。このコンポーネントが別のコンポーネントに追加されていることが原因である可能性がありますか?リアクト

複数コピー

npm ls | grep react ├─┬ [email protected] ├── [email protected] ├── [email protected] extraneous ├── [email protected] ├─┬ [email protected] │ ├─┬ [email protected] 

はどちらか重複したパッケージがあるように思えないのですか?ここで何が起こっているのでしょうか?

答えて

0

私は同様の問題があり、文字列リファレンスを使用しないことで解決できました。

グッド:

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

悪い:

<input ref="textInput" /> 

チェックアウトここドキュメント:

を「あなた場合:彼らは実際にそれをしないと言う https://facebook.github.io/react/docs/refs-and-the-dom.html

前にReactで作業していた場合、古いAPIに精通している可能性がありますe ref属性は "textInput"のような文字列であり、DOMノードはthis.refs.textInputとしてアクセスされます。文字列リファレンスにはいくつかの問題があり、レガシーと見なされ、将来のリリースのいずれかで削除される可能性があるので、これに対して反対することをお勧めします。現在、this.refs.textInputを使用して参照情報にアクセスしている場合は、代わりにコールバックパターンを使用することをお勧めします。 "

+0

複数の質問に同じ回答を投稿しないでください。質問が重複ではない場合は、*あなたの質問に対する回答を調整してください。* –

関連する問題