Reactのイベントハンドリング

Tuyoshi Akiyama
Jul 20, 2017 · 2 min read

前回の記事の続きになります。

Event handling

以下コード例を見ていきます。

簡単なon offスイッチをReactで書いています。

ES6クラスを使用してコンポーネントを定義する場合、event handlerがクラスのメソッドになるのが、一般的なパターンになります。

たとえば、このToggleコンポーネントは、ユーザーが「ON」と「OFF」の状態を切り替えるためのボタンを、handleClick(event handler)を用いてレンダリングしています。

また、JSXコールバックでは、thisの意味に注意する必要があります。 JavaScriptでは、クラスメソッドはデフォルトでバインドはされていません。

つまりthis.handleClickをバインドしてonClickに渡すのを忘れた場合、関数が実際に呼び出されるとき未定義になります。

これは、JavaScriptでの関数の動作仕様からくるものです。

一般的に、onClick = {this.handleClick}のように後に()を付けないメソッドを参照する場合は、そのメソッドをバインドする必要があります。

つまり、constructor()内にある

this.handleClick = this.handleClick.bind(this);

でthisをバインド処理して、this keywordが何を参照しているのかを、設定する必要があるということになります。

)
Welcome to a place where words matter. On Medium, smart voices and original ideas take center stage - with no ads in sight. Watch
Follow all the topics you care about, and we’ll deliver the best stories for you to your homepage and inbox. Explore
Get unlimited access to the best stories on Medium — and support writers while you’re at it. Just $5/month. Upgrade