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);
});
}