0
1

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】アロー関数とbind()の参照するthis

Last updated at Posted at 2019-12-21

参照するthisについての話

アロー関数とbind()についての大事な特徴を理解したのでメモ.これを理解していなかったのでクリック時のイベントハンドラでエラー吐き出されるはめになった.

アロー関数

func = (arg) => {}

これがアロー関数の形.関数との違いは参照するthisの場所.普通の関数はグローバルなthisを参照するけど,アロー関数では呼び出し元のthisを参照する.

let this.str = "global";

function func() {
  console.log(this.data);
}

arrowFunc = () => {
  console.log(this.data);
};

const f = {
  data: 'local',
  execute: func
};
f.execute();
// => 'global'

const af = {
  data: 'local',
  execute: arrowFunc
};
af.execute();
// => 'local'

イベントハンドラでは呼び出し元のthis.stateを参照したいからアロー関数を使うべき.

bind()

アロー関数でなくとも,関数の参照thisをbind()で呼び出し元のthisに紐づける方法もある.

constructor(props) {
    super(props);
    this.state = { isToggleOn: true };
    // このオブジェクトをイベントハンドラの内部のthisに結びつける
    this.handleClick = this.handleClick.bind(this);
  }

handleClick() {}

render() { <button onClick={this.handleClick}></button> }

bind()で一行増やすくらいなら自分はアロー関数を使おうかと思います.可読性もアロー関数の方が上がりそう.

0
1
0

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
0
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?