使用react的过程中,如果把事件写入到JSX中会导致代码混乱,推荐将逻辑抽离到单独的方法中,保证JSX结构清晰。但是将逻辑抽离到单独的方法中就会this指向的问题。本文介绍3个解决事件绑定this指向问题的方案。

class App3 extends React.Component{
  // 初始化state
  state={
    count:0
  }
  render(){
    // js逻辑代码写入JSX中导致代码显得混乱
    return (
      <div><h1>计数器:{this.state.count}</h1>
          <button onClick={()=>{
            this.setState({
              count:this.state.count + 1
            })
          }}>+1</button>
      </div/>
    )
  }
}
// 渲染组件
ReactDOM.render(<App3 />,document.querySelector('#root'))

1.箭头函数方法

利用箭头函数自身不绑定this的特点

render()方法中的this为组件实例,可以获取到setState()

class App4 extends React.Component{
  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>
    )
  }
}
// 渲染组件
ReactDOM.render(<App4 />,document.querySelector('#root'))

2.Function.prototype.bind()

利用ES5中的bind方法,将事件处理程序中的this与组件实例绑定到一起

class App5 extends React.Component{
  constructor(){
    super()
    this.state={
      count: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>
    )
  }
}
// 渲染组件
ReactDOM.render(<App5 />,document.querySelector('#root'))

3.class的实例方法

利用箭头函数形式的class实例方法解决this指向问题

class App6 extends React.Component{
  constructor(){
    super()
    this.state={
      count: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>
    )
  }
}
// 渲染组件
ReactDOM.render(<App6 />,document.querySelector('#root'))
评论
头像
验证码:
相关推荐

七年之痒是什么意思

520送什么给女友

第一次见女方父母送什么好




如果未经特殊说明,本站内容皆为原创,转载内容如果侵犯了您的权益,如有侵权请联系管理员删除
联系QQ:2380712278

备案号:皖ICP备19012824号