2016-05-20 4 views
2

this.props.childrenに関数を渡す必要があります。子コンポーネントに関数を渡すthis.props.childrenメソッドが未定義

updateBarTitle(barTItle){ 
    this.setState({barTItle}); 
} 
render(){ 
    const children = React.Children.map(this.props.children, function (child) { 
     return React.cloneElement(child, { 
      updateBarTitle: this.updateBarTitle 
     }); 
     }); 
    {children} 
} 

しかし、私はUncaught TypeError: Cannot read property 'updateBarTitle' of undefinedを得続けます。

また、私はこれが最善の方法だろうと思いますか?ここでの目標は、子の値に基づいて親の状態を更新することです。だから私はどちらかと思っていた。親が作成した関数を渡した後、子はそれを更新するか、親によって子の状態にアクセスします。例は大きな助けになるでしょう。

答えて

4

thisは、適切なコンテキストにバインドされていません。あなたは3回目の引数としてthisを渡すことで、それをバインドすることができます。

const children = React.Children.map(this.props.children, function (child) { 
    return React.cloneElement(child, { 
     updateBarTitle: this.updateBarTitle 
    }); 
}, this); 

またはコンテキストを盗むしない矢印の機能を使用します。

const children = React.Children.map(this.props.children, (child) => { 
    return React.cloneElement(child, { 
     updateBarTitle: this.updateBarTitle 
    }); 
}); 
+0

感謝を!、私の現在のアプローチは、私の親コンポーネントを更新するには正しいだろう私はむしろ子から状態の値を取得するだけですか? – Tony

+0

@Tony IMHO関数(ハンドラ、アクション)を子プロップに渡すと、反応がうまくいきます。私はその好む方法を言うだろう.. – madox2

関連する問題