简体   繁体   中英

React: Why do we not need to bind context to arrow functions being used as event listeners?

Looking at the react tutorial it explains that when we set event listeners, we generally have to bind the functions context, like is done here

class Toggle extends React.Component {
  constructor(props) {
    super(props);
    this.state = {isToggleOn: true};

    // This binding is necessary to make `this` work in the callback
    this.handleClick = this.handleClick.bind(this);
  }

  handleClick() {
    this.setState(state => ({
      isToggleOn: !state.isToggleOn
    }));
  }

  render() {
    return (
      <button onClick={this.handleClick}>
        {this.state.isToggleOn ? 'ON' : 'OFF'}
      </button>
    );
  }
}

I understand this, because unless we bind context to the this.handleClick function we have no guarantee of what value this will actually hold when we call this.setState within the handleClick function. However, the tutorial goes on to state that we would not have to bind context to the handleClick function if we replaced <button onClick={this.handleClick}> with <button onClick={() => this.handleClick}>

How come the correct this context is automatically bound when we use an arrow function?

You don't need to but arrow functions keep context of this as the object that defined them where traditional function context this as the object that calls them. You can use normal functions as long as they don't call this or keep a reference to this with a variable link const self = this and use self instead of this.

Why is this the case? Because they designed it to be so.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM