フロントエンジニア芸人もりたけんじのreact

【React】子供のメソッドを親から呼びたい!!ref/refs使ったら「Uncaught 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」

【React】子供のメソッドを親から呼びたい!!ref/refs使ったら「Uncaught 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」

親のコンポーネントからレンダー内で読み込んでいる子コンポーネント内のメソッドを呼びたいのですが、
上のようなエラー出ることがあります。

Referrence
https://facebook.github.io/react/warnings/refs-must-have-owner.html
https://facebook.github.io/react/tips/expose-component-functions.html

Uncaught 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
Uncaught 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

解決策の一つにこのようなのがあります。

参照したいrender内のreturn内にあるChildComponentに
このようにして、

[code language="javascript"]
<ChildComponent ref={(child) => this.child = child} />
[/code]

ref={(child) => this.child = child}
として、

呼び出す側のメソッド内で、子供にある「_callParent」を呼びたかったら
こう。

[code language="javascript"]
_hoge() {
this.child._callParent();
}
[/code]

this.childが子供のコンポーネント内への参照になります。
これで親から子供のインスタンスメソッドが呼べる。

解決記事
https://stackoverflow.com/questions/32502165/react-cant-call-a-function-inside-child-component

【 関連記事 】
【REACT】REACTの動きを理解したい人の為の最小サンプル
【REACT入門】過去のREACT初心者の自分にREACTのPROPSとSTATEの違いを簡単に説明してあげたい
【REACT × ES6 × FLUX】を手っ取り早く学びたい人の為にサンプル作ったよ【3の倍数と3が付くときだけ猫になるCOUNTER】
REACT × FLUX × ES6 [WIP]LINE風チャット
他のReact記事
フロントエンド記事
github
qiita