Reactガイドを読んでいくその8
これは
Reactのガイドを読んでいく記事です。
ガイドのリンク
イベント処理
昨日の続きです。
JSXのコールバックにおけるthisの意味に注意が必要。
JavaScriptではクラスのメソッドはデフォルトでバインドされない。
なので、this.handleClickへのバインドをせずにonClickに渡した場合thisはundefindになる。
バインドしない方法として2つある。
CreateReactAppでデフォルト有効になっている、パブリッククラスフィールド構文を使用する方法。
class LoggingButton extends React.Component { // This syntax ensures `this` is bound within handleClick. // Warning: this is *experimental* syntax. handleClick = () => { console.log('this is:', this); } render() { return ( <button onClick={this.handleClick}> Click me </button> ); } }
もう一つはコールバック内でアロー関数を使用する方法。
class LoggingButton extends React.Component { handleClick() { console.log('this is:', this); } render() { // This syntax ensures `this` is bound within handleClick return ( <button onClick={(e) => this.handleClick(e)}> Click me </button> ); } }
イベントハンドラに引数を渡す
Reactイベントを表すeという引数はIDの次の2番目の引数として渡される。
// アロー関数がイベントハンドラに追加パラメータを渡す役割 <button onClick={(e) => this.deleteRow(id, e)}>Delete Row</button> // Function.prototype.bindがパラメータを渡す役割 <button onClick={this.deleteRow.bind(this, id)}>Delete Row</button>
今日はここまで。