Reactでは、一般的に他のコンポーネントに渡すメソッドについてはバインドする必要があります。
例えば、React.Componentクラス内で、increment()関数を定義し、
子コンポーネントに関数を渡したい場合は,
Function.prototype.bind()
でbindしなければなりません。
イベントハンドラやその他の関数をprops
として、子コンポーネントに渡すようにします。
例えば、increment()という関数がある場合には以下のようにして、propsとして渡します。
<button onClick={this.increment}>
関数をthisキーワードをバインドする方法は主に2つで、
があります。
increment関数をコンポーネントインスタンスにバインドする方法は以下のようになります。
class App extends React.Component {
constructor(props) {
super(props);
this.increment = this.increment.bind(this);
}
increment() {
this.setState({
count: this.state.count + 1,
});
}
}
コンストラクタ内で、Function.prototype.bind()
メソッドを利用し、
thisキーワードをバインドしたincrement関数をthis.increment
に代入しています。
これにより、increment関数内でReact.ComponentのSetState()
を利用できています。
increment関数をクラスのプロパティとして定義することでも同様の動作となります。
class App extends React.Component {
constructor(props) {
super(props);
}
increment = () => {
this.setState({
count: this.state.count + 1,
});
};
}