Value of this in React event handler

你离开我真会死。 提交于 2019-11-26 17:45:25
WiredPrairie

This is correct behavior for JavaScript and React if you use the new class syntax.

The autobinding feature does not apply to ES6 classes in v0.13.0.

So you'll need to use:

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

Or one of the other tricks:

export default class Observer extends React.Component {
  constructor() {
    super();
    this.handleClick = this.handleClick.bind(this);
  }
  handleClick() {
    /* ... */
  }
  render() {
      return <button onClick={this.handleClick}>Click</button>
  }
}

The accepted answer is good and I've used it a lot in ES6, but I just want to add another "more modern" solution we have with ES7 (mentioned in the React component class auto-binding notes): use arrow functions as class properties, then you don't need to bind or wrap your handler anywhere.

export default class Observer extends React.Component {
  handleClick = (e) => {
    /* ... */
  }
  render() {
      return <button onClick={this.handleClick}>Click</button>
  }
}

This is the simplest and cleanest solution yet!

Like others have said, React doesn't autobind methods to the instance when using ES6 classes. That said, I would make habit of always using arrow functions in event handlers like: onClick={e => this.handleClick()}

Instead of: onClick={this.handleClick.bind(this)}

This because it means that you can replace the handleClick method with a spy in a test, something you can't do when you use bind.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!