LoginSignup
0
0

More than 3 years have passed since last update.

Reactプロジェクトで this.hoge.bind(this) とかやってる人に言いたい

Posted at

これを見てくれ

class CoolButton {
  constructor() {
    this.onClick.bind(this);
  }

  onClick() {
    ...
  }

  render() {
    return <button onClick={this.onClick}>Cool</button>;
  }
}

このbindを見て疑念を抱いた君、正解だ
イベントハンドリング部分でアロー関数でイベントを書くようにすればこんなthisは要らない

class CoolButton {
  onClick() {}

  render() {
    return <button onClick={() => this.onClick()}>Cool</button>;
  }
}

結論

onHogehoge のようなイベントはアロー関数で指定してあげよう

0
0
2

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0