222
Help us understand the problem. What are the problem?

More than 5 years have passed since last update.

posted at

updated at

Reactをes6で使う場合のbindの問題

es6でReact.Componentを作成した場合
イベントハンドラでthisがundefinedになる

es5のReact.createClassを使った場合は、
イベントハンドラが自動でbindされるので大丈夫だった

es6

save(e){
    this.props // undefined になる
}
render (){
    return (
        <button onClick={this.save} />保存</button>
    );
}

es5


save = function (e){
    this.props // undefined ではない
}
render = function (){
    return (
        <button onClick={this.save} />保存</button>
    );
}

解決策1

constructor内でbind


constructor() {
    super();
    this.save = this.save.bind(this);
}
render = function (){
    return (
        <button onClick={this.save} />保存</button>
    );
}

解決策 2

jsx内でbind


render = function (){
    return (
        <button onClick={this.save.bind(this)} />保存</button>
    );
}

解決策 3

es6のアローファンクションを使う
eventを渡す必要がある


render = function (){
    return (
        <button onClick={(event) => this.save(event)} />保存</button>
    );
}

解決策 4

es7の新しいbindシンタックスを使う
※これはwebstormで構文エラーになる


render = function (){
    return (
        <button onClick={::this.save} />保存</button>
    );
}
Why not register and get more from Qiita?
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away
Sign upLogin
222
Help us understand the problem. What are the problem?