property initializer syntaxを使うとbindが不要
2131 ワード
bind問題
ReactのコンポーネントをES6のクラス構文で書く場合、コンストラクタ内でメソッドをbindする処理を逐一書く必要があります。
class Toggle extends React.Component {
constructor(props) {
super(props);
this.state = {isToggleOn: true};
// This binding is necessary to make `this` work in the callback
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')
);
メソッドの数が増えるにつれて、この記述は面倒です。
property initializer syntaxを使う
ReactのチュートリアルのHandling Eventsには、property initializer syntaxを使うと、bindが不要になるという説明がありました。
このように、メソッドをアロー関数で書くと、babelのコンパイル時に内部で、bindしてくれるようです。
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>
);
}
}
property initializer syntaxを使い方は、こちらを参照してください。
Create React Appなら、設定不要
Create React App で作られたReactプロジェクトは、デフォルトでproperty initializer syntaxが有効になっているようです。
Author And Source
この問題について(property initializer syntaxを使うとbindが不要), 我々は、より多くの情報をここで見つけました https://qiita.com/takaken/items/8375247778a51f5a42ff著者帰属:元の著者の情報は、元のURLに含まれています。著作権は原作者に属する。
Content is automatically searched and collected through network algorithms . If there is a violation . Please contact us . We will adjust (correct author information ,or delete content ) as soon as possible .