VOOZH about

URL: https://qiita.com/cubdesign/items/ee8bff7073ebe1979936

⇱ Reactをes6で使う場合のbindの問題 #React - Qiita


👁 Image
255

Go to list of users who liked

219

Share on X(Twitter)

Share on Facebook

Add to Hatena Bookmark

More than 5 years have passed since last update.

@cubdesign(Takeo Tamura)

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

255
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

Go to list of users who liked

219
6

Go to list of comments

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

Go to list of users who liked

219