React事件中this指向的问题

一,绑定事件时this的指向

import { Component } from 'react'
import ReactDOM from 'react-dom'

class This extends Component {
  state = {
    msg: 'hello react'
  }

  handleClick () {
    console.log(this) // 这里的this是?   答案: 此时this指向undefined
  }

  render () {
    console.log(this) // 这里的this是?   答案: 此时this指向APP实例
    return (
      <div>
        <button onClick={this.handleClick}>点我</button>
      </div>
    )
  }
}
ReactDOM.render(<This />, document.getElementById('root'))

分析原因:

  • 事件处理程序的函数式函数调用模式,在严格模式下,this指向undefined
  • render函数是被组件实例调用的,因此render函数中的this指向当前组件

解决方案:

  1. Function.prototype.bind() ,利用bind改变this指向
  2. 箭头函数【推荐】
  3. class 的实例方法
import { Component } from 'react'
import ReactDOM from 'react-dom'

class This extends Component {
  state = {
    msg: 'hello react'
  }

  handleClick () {
    console.log(this.state.msg)
  }

  changeTab = () => {
    console.log(this.state.msg)
  }

  render () {
    return (
      <div>
        {/* // 方案1:在事件中加入箭头函数 */}
        <button
          onClick={() => {
            this.handleClick()
          }}>
          点我1
        </button>
        {/* // 方案2: */}
        <button onClick={this.changeTab}>点我2</button>
        {/* // 方案3:利用bind()方法改变this指向 */}
        <button onClick={this.handleClick.bind(this)}>点我3</button>
      </div>
    )
  }
}
ReactDOM.render(<This />, document.getElementById('root'))

结果:

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值