LoginSignup
7
3

More than 5 years have passed since last update.

react es6 bind記述パターン

Last updated at Posted at 2017-04-19

es6記法でReactComponentを使う場合のbind記述パターンはいくつかある

1. constructorでbind(this)する

この書き方が一番多い気がする

import { Component } from 'react'

class Sample extends Component {
  constructor() {
    super();
    this._handleClick = this._handleClick.bind(this);
  }
}

2. Allow functionを使う

import { Component } from 'react'

class Sample extends Component {
  constructor() {
    super();
  }

  _handleClick = () => console.log("click!!")

  return (
    <div onClick={this._handleClick}>click</div>
  )
}

3. es7の::を使う

import { Component } from 'react'

class Sample extends Component {
  constructor() {
    super();
  }

  _handleClick() {
    console.log("click!!")
  } 

  return (
    <div onClick={::this._handleClick}>click</div>
  )
}

※::対応ではうまくbindできないケースもありましたので、確実なのは1か2。

4.おまけ

1の書き方をしている派が多いようにみえるが、bindするメソッドが多い場合に
bind(this)をひたすら書くのは美しくないのでloadshのforEachを使う

import { Component } from 'react'
import _ from 'lodash'

class Sample extends Component {
  constructor() {
    super();
  }
  _.forEach([
      '_method1',
      '_method2',
      '_method3'
  ], (method) => {
      this[method] = this[method].bind(this);
  });
}
7
3
0

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
7
3