首页 >社区问答列表 >javascript - React中组件绑定this

javascript - React中组件绑定this

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

想不明白这里的this绑定

  • 三叔
  • 三叔    2017-06-28 09:28:212楼

    因为在class中声明函数,并不会自动绑定this对象

    所以,你在onClick={this.handleEvent}的时候,分解成两步你就懂了:

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

    所以,onClick调用的时候,handleEvent中的this会是undefined(根据文档)

    所以,你需要bind一下, 那么里面的this就是当前组件啦。

    还有一种方便的写法,就是用箭头函数声明:

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

    +0添加回复

  • 回复
  • 给我你的怀抱
  • 给我你的怀抱    2017-06-28 09:28:211楼

    因为handleEvent中this.setState...
    的this并没有绑定this

    可以采用箭头函数的语法糖来绑定this

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

    +0添加回复

  • 回复