概要
Reactでイベントハンドリングするときに関数が未定義だよって言われたことありません?あっ、ないんですか、、そうですか、、、。
3つの方法で回避
バインディングしよう
これが基本らしいよ
class Toggle extends React.Component {
constructor(props) {
super(props);
this.state = {isToggleOn: true};
// !これが必要!
this.handleClick = this.handleClick.bind(this);
}
handleClick() {
this.setState(prevState => ({
isToggleOn: !prevState.isToggleOn
}));
}
render() {
return (
<button onClick={this.handleClick}>
{this.state.isToggleOn ? 'ON' : 'OFF'}
</button>
);
}
}
ReactDOM.render(
<Toggle />,
document.getElementById('root')
);
public class fields syntax?を使う
つまりこんな感じで書く
class LoggingButton extends React.Component {
// This syntax ensures `this` is bound within handleClick.
// Warning: this is *experimental* syntax.
// !ここね!
handleClick = () => {
console.log('this is:', this);
}
render() {
return (
<button onClick={this.handleClick}>
Click me
</button>
);
}
}
create-react-appではこれがデフォルトやねんて、俺もこれ使お
アロー関数を使う
なるほど〜
class LoggingButton extends React.Component {
handleClick() {
console.log('this is:', this);
}
render() {
// This syntax ensures `this` is bound within handleClick
return (
<button onClick={(e) => this.handleClick(e)}>
Click me
</button>
);
}
}
余談:引数渡すとき
<button onClick={(e) => this.deleteRow(id, e)}>Delete Row</button>
<button onClick={this.deleteRow.bind(this, id)}>Delete Row</button>
🙆
全部このチュートリアルに書いてあった話