MENU

React イベントに関数を渡す時

イベントに監視を渡すとき

式展開で渡すと.setStateするときに、thisがundefinedになりエラーになる

  handleLogin() {
    this.setState({loggedIn: !this.state.loggedIn})
  } 

  <Botton onClick={this.handleLogin}}>ログイン</Botton>
 

対処方法

  • 対処方1

thisをbindする

 <Botton onClick={this.handleLogin.bind(this)}>ログイン</Botton>
  • 対処方法2

即時関数で実行する

 <Botton onClick={() => {this.handleLogin()}}>ログイン</Botton>