React 类组件 this 写法

本文探讨了在React组件中,`this`在回调函数中可能为`undefined`导致无法访问`setState`的问题。文章提供了两种解决方法:1) 在构造函数中使用`bind`来绑定`this`;2) 使用箭头函数定义回调。这两种方法都能确保`this`正确指向组件实例,从而能够正常更新状态。通过理解`this`的工作原理,开发者可以更好地编写React代码。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

先看一段代码,其 this 指向需要修正

import React from "react";

class Comp extends React.Component {
  state = { a: 1 }
  handleClick() {
    console.log(this, 'handleClick');  // undefined 'handleClick'
    this.setState({ a: this.setState.a + 1 })  // 报错 Cannot read properties of undefined (reading 'setState')
  }
  render() {
    return (
      <div className="comp">
        <span>{this.state.a}</span>
        <button onClick={this.handleClick}>click</button>
      </div>
    )
  }
}

上诉代码中是属于在 react 中 this 有问题的写法,在handleClick 方法中 this是 undefined ,所以我们就无法使用 this.setState 去修改 state 数据状态,为什么呢?就因为 this 是 undefined ,你咋去访问 setState 方法。

但是我就是非要这么写,怎么整?

方法1,通过在 constructor 里面修改 this 指向

class Comp extends React.Component {
  constructor() {
    super()
    // console.log(this); 在这里 this 能输出
    this.handleClick = this.handleClick.bind(this)  // 强行修改 this 指向
  }
  state = { a: 1 }
  handleClick() {
    console.log(this, 'handleClick');  // Comp {props: {…}, context: {…}, refs: {…}, updater: {…}, state: {…}, …} 'handleClick'
    this.setState({ a: this.state.a + 1 })  // 该方法能访问使用
  }
  render() {
    return (
      <div className="comp">
        <span>{this.state.a}</span>
        <button onClick={this.handleClick}>click</button>
      </div>
    )
  }
}

方法2,箭头函数写法,访问 render 的 this

下述代码在表达式中通过使用箭头函数来修改 this ,使其指向父级 render函数 的 this ,render函数里面的 this 是可以访问的(在其 react 内部就做了修改,指向实例对象),不同于上述的 handleClick

class Comp extends React.Component {
  state = { a: 1 }
  render() {
    return (
      <div className="comp">
        <span>{this.state.a}</span>
        <button onClick={() => this.setState({ a: this.state.a + 1 })}>click</button>
      </div>
    )
  }
}

所以说,别跟这个 this 过意不去,最通用的写法吧,绿色环保,安全无误

class Comp extends React.Component {
  state = { a: 1 }
  handleClick = () => {
    console.log(this, 'handleClick');  // Comp {props: {…}, context: {…}, refs: {…}, updater: {…}, state: {…}, …} 'handleClick'
    this.setState({ a: this.state.a + 1 })
  }
  render() {
    return (
      <div className="comp">
        <span>{this.state.a}</span>
        <button onClick={this.handleClick}>click</button>
      </div>
    )
  }
}

ES6 class 语法
ES6 class 继承

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值