255
218

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

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

Last updated at Posted at 2015-07-28

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>
	);
}
255
218
6

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
255
218

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?