三种方法解决React类组件中this指向问题

从onClick事件不加括号说起

import React from 'react'
import './App.css'
class TestComponent extends React.Component {
  clickHandler () {
    console.log('111')
    console.log('this指向:', this)
  }
  render () {
    return (
      <button onClick={this.clickHandler()}>点击我</button>
    )
  }
}
function App () {
  return (
    <div>
      <TestComponent></TestComponent>
    </div>

  )
}

export default App

预想的功能是点击按钮后控制台输出111和this指向,但实际是渲染后会立即执行此方法,不用点击按钮,已经输出了对应信息:

在这里插入图片描述
这是因为在react的jsx语法中,{}的作用就是执行,在js表达式中加()相当于是调用函数,也就是this.clickHandler被立即执行了。

不加()会怎么样?刷新页面,没有输出信息,点击按钮,输出了信息,看起来好像解决了问题,但此时会发现this指向变了:
在这里插入图片描述

解决方法

解决上述this指向问题,有三种解决方法

1. public class fields(最推荐)

文档
用法:使用箭头函数形式的实例方法,clickHandler = () => {}

import React from 'react'
import './App.css'
class TestComponent extends React.Component {
  clickHandler = () => {
    console.log('111')
    console.log('this指向:', this)
  }
  render () {
    return (
      <button onClick={this.clickHandler}>点击我</button>
    )
  }
}
function App () {
  return (
    <div>
      <TestComponent></TestComponent>
    </div>

  )
}

export default App

2. 箭头函数

箭头函数特点:

  1. 箭头函数声明赋值给点击事件,但未执行,只有触发点击后才会被执行
  2. 箭头函数中的this实际是外层函数的this

用法:在事件绑定位置使用箭头函数,onClick={() => this.clickHandler()}

import React from 'react'
import './App.css'
class TestComponent extends React.Component {
  clickHandler () {
    console.log('111')
    console.log('this指向:', this)
  }
  render () {
    return (
      <button onClick={() => this.clickHandler()}>点击我</button>
    )
  }
}
function App () {
  return (
    <div>
      <TestComponent></TestComponent>
    </div>

  )
}

export default App

3. constructor 中通过bind绑定this

相当于在类组件初始化阶段就将回调函数的this修正为永远指向当前组件实例对象,this.clickHandler = this.clickHandler.bind(this)

import React from 'react'
import './App.css'
class TestComponent extends React.Component {
  constructor() {
    super()
    this.clickHandler = this.clickHandler.bind(this)
  }
  clickHandler () {
    console.log('111')
    console.log('this指向:', this)
  }
  render () {
    return (
      <button onClick={this.clickHandler}>点击我</button>
    )
  }
}
function App () {
  return (
    <div>
      <TestComponent></TestComponent>
    </div>

  )
}

export default App

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值