supNate
supNate

Reputation: 430

What is this syntax of defining a method in a React component with ES6

As you know we can use ES6 in React since 0.13. And I found below syntax to define an event handler:

class MyComponent extends React.Component {
  handleClickEvent = evt => {
    this.setState({value: evt.target.value});
  }
  render() {
    return <div onClick={this.handleClickEvent} />;
  }
}

By this syntax we don't need to use this.handleClickEvent.bind(this). I've searched a lot but still didn't find out why this in the method handleClickEvent is in the correct scope. Anyone could help? Thanks in advance!

Upvotes: 2

Views: 119

Answers (1)

Oleksandr T.
Oleksandr T.

Reputation: 77522

Because you are using => arrow function.,

Arrow functions do not have their own this value. The value of this inside an arrow function is always inherited from the enclosing scope.

Arrow functions

With not arrow functions you should you should set this to function by yourself

class MyComponent extends React.Component {
  constructor() {
    super();
    this.handleClickEvent = this.handleClickEvent.bind(this);
    //                                           ^^^^^^^^^^^
  }

  handleClickEvent() {
    this.setState({value: evt.target.value});
  }

  render() {
    return <div onClick={this.handleClickEvent} />;
  }
}

Upvotes: 5

Related Questions