react事件绑定this指向

77 阅读1分钟

在react中绑定事件,最终要的就是要考虑好this的指向,个人认为call的实例方法,充分利用了箭头函数的特性,自身不绑定this,外部环境的this是谁,里边的this就是谁

推荐: 使用call的实例方法

class APP extends React.Componet{ 
    state={ 
      count:0 
    1} 
    //事件处理函数 
     onIncrement = () =>{ 
       console.log('事件处理函数的this',this) 
       this.setState({
           count:this.state.count + 1 
    })
 } 
 render(){ 
    return(
     <div>
      <h1>计数器:{this.state.count}</h1>
      <button onClick={this.onIncrement}>点我+1</button>
    </div> 
    ) 
  }  
}

箭头函数

class APP extends React.Componet{
    state={
       count:0
    }
    //事件处理函数
    onIncrement(){
        console.log('事件处理函数的this',this)
        this.setState({
            count:this.state.count + 1
        })
    }
   render(){
     return(
     <div>
         <h1>计数器:{this.state.count}</h1>
         <button onClick={()=>this.onIncrement()}>点我+1</button>
     </div>
     ) 
   }
}

bind

class APP extends React.Componet{
constructor(){
   state={ 
      count:0 
   } 
  this.state = {
  conunt:0
  } 
  this.onIncrement = this.onIncrement.bind(this)
}
    //事件处理函数
  onIncrement(){ 
       console.log('事件处理函数的this',this)              this.setState({
           count:this.state.count + 1 
        })
     } 
  render(){
    return( 
       <div> 
          <h1>计数器:{this.state.count}</h1> 
          <button onClick={this.onIncrement}>点我+1</button>
       </div> 
       ) 
     }
  }