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 (
      

事件绑定

) } } const app = (
) ReactDom.render(app, document.getElementById('root'))

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

react中绑定事件this指向问题_第1张图片

react中绑定事件this指向问题_第2张图片

请看demo

react中绑定事件this指向问题_第3张图片

react中绑定事件this指向问题_第4张图片

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

react中绑定事件this指向问题_第5张图片

react中绑定事件this指向问题_第6张图片

react中绑定事件this指向问题_第7张图片

 2.解决方案

 解决方案有如下三种

  1. Function.prototype.bind()

  2. 箭头函数

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

2.1  bind方法

react中绑定事件this指向问题_第8张图片

2.2 箭头函数

react中绑定事件this指向问题_第9张图片

 2.3class 的实例方法【推荐】

 react中绑定事件this指向问题_第10张图片

 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 (
      

事件绑定

) } } const app = (
) ReactDom.render(app, document.getElementById('root'))

你可能感兴趣的:(react.js,javascript,前端)