Help us understand the problem. What is going on with this article?

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

More than 3 years have passed since last update.

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>
    );
}
infas
出版とデジタルの事業領域で、独創性あふれるプロフェッショナル集団としてチャレンジ精神をもって常に市場ニーズを先取りし、新しい価値と文化を創造しつつ、時代の変化に挑戦し続けることを使命とします。ファッション週刊誌「WWD JAPAN」「WWD BEAUTY」、カルチャー誌「STUDIO VIOCE」を発行。
http://www.infaspub.co.jp/
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
Comments
No comments
Sign up for free and join this conversation.
If you already have a Qiita account
Why do not you register as a user and use Qiita more conveniently?
You need to log in to use this function. Qiita can be used more conveniently after logging in.
You seem to be reading articles frequently this month. Qiita can be used more conveniently after logging in.
  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
ユーザーは見つかりませんでした