sunmingtao / sample-code

3 stars 4 forks source link

What's the purpose of bind(this) in onClick? #60

Closed sunmingtao closed 4 years ago

sunmingtao commented 4 years ago
class App extends React.Component {
  constructor(props){
      super(props);
      this.state = {
        name: props.name
      };
   }

  changeName(){
    this.setState({
        name: 'Anna'
    });
  }

  render(){
    return (
        <div>
        <p>{this.state.name}</p>
        <button id="btn" onClick={this.changeName.bind(this)}>Change name</button>
      </div>
    );
  }
}

ReactDOM.render(<App name="smt"/>, document.querySelector('#app'));
sunmingtao commented 4 years ago

Print this to console. It shows this refers to the App object

changeName(){
    console.dir(this);
    this.setState({
        name: 'Anna'
    });
  }

Now remove .bind(this), this evaluates to undefined (why? I thought it should be the button)

So bind(this) ensures the this in changeName() method refers the App object.

Alternatively, we can change the changeName() to an arrow function

changeName = () => {
    this.setState({
        name: 'Anna'
    });
  }

.bind(this) then becomes unnecessary.

onClick={this.changeName} is good enough.

When a function is defined as arrow function, this always refers to the object in which the function is defined, regardless which object calls the function.