search

Home  >  Q&A  >  body text

javascript - Component binding this in React

<button onClick={this.handleEvent}>    //这里的this是toggle组件 为什么还需要在组件里绑定这个函数的this 
  {this.state.isToggleOn === true ? 'on' : 'off'}
</button>

I don’t understand the this binding here

大家讲道理大家讲道理2804 days ago798

reply all(2)I'll reply

  • 三叔

    三叔2017-06-28 09:28:21

    Because when a function is declared in class, it will not be automatically bound to thisobject

    So, when you onClick={this.handleEvent}, break it down into two steps and you will understand:

    let handleEvent = this.handleEvent;
    ...onClick={handleEvent}...

    So, when onClick is called, this in handleEvent will be undefined (according to the documentation)

    So, you need to bind, then this inside is the current component.

    There is also a convenient way to write it, which is to declare it with an arrow function:

    handleEvent = (e)=>{
    
    }
    
    render(){
      ...onClick={this.handleEvent}...
    }

    reply
    0
  • 给我你的怀抱

    给我你的怀抱2017-06-28 09:28:21

    Because this.setState...
    in handleEvent is not bound to this

    You can use the syntactic sugar of arrow functions to bind this

    handleEvent = () => {
        this.setState...
    }

    reply
    0
  • Cancelreply