LoginSignup
5

More than 5 years have passed since last update.

property initializer syntaxを使うとbindが不要

Last updated at Posted at 2017-03-20

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が有効になっているようです。

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
5