react中绑定事件this指向问题

1.this指向问题 

import { Component } from 'react'
import ReactDom from 'react-dom'
class Com1 extends Component {
  constructor () {
    super()
    this.state = {
      num: 100
    }
  }

  hClick () {
    // alert(1)
    console.log(this)
  }

  render () {
    return (
      <div>
        <h1>事件绑定</h1>
        <button onClick={this.hClick}>绑定事件</button>
      </div>
    )
  }
}
const app = (
  <div>
    <Com1 />
  </div>
)
ReactDom.render(app, document.getElementById('root'))

如图  我在一个类创建的组件中打印了render中的this和绑定事件的this  打印的结果render是指当前实例  绑定事件的this却是undefined    这是什么原因呢

请看demo

此时我如果开启了严格模式  this就指向undefined  

 2.解决方案

 解决方案有如下三种

  1. Function.prototype.bind()

  2. 箭头函数

  3. class 的实例方法【推荐】

2.1  bind方法

2.2 箭头函数

 2.3class 的实例方法【推荐】

 

 3.三种解决方案完整代码

import { Component } from 'react'
import ReactDom from 'react-dom'
class Com1 extends Component {
  constructor () {
    super()
    this.state = {
      num: 100
    }
  }

  hClick1 () {
    // alert(1)
    console.log('hClick1', this)
  }

  hClick2 () {
    console.log('hClick2', this)
  }

  hClick3 = () => {
    console.log('hClick3', this)
  }

  render () {
    console.log('render', this)
    return (
      <div>
        <h1>事件绑定</h1>
        <button onClick={this.hClick1.bind(this)}>bind方法解决</button>
        <button
          onClick={() => {
            this.hClick2()
          }}>
          回调函数解决
        </button>
        <button onClick={this.hClick3}>class类方法解决</button>
      </div>
    )
  }
}
const app = (
  <div>
    <Com1 />
  </div>
)
ReactDom.render(app, document.getElementById('root'))

  • 7
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值