React类组件中事件处理函数中的 this 指向问题

目标

  1. 给按钮绑定点击事件

  2. 获取原来的数字

  3. 在原来数字的基础上 +1

 

import React, { Component } from 'react'

const center = 'center'

export default class App extends Component {
  state = {
    count: 0,
  }
  handleClick() {
    // 期望:this 是实例对象
    console.log(this) 
  }
  render() {
    return (
      <div style={{ textAlign: center }}>
        <h2>计数器:{this.state.count}</h2>
        {/* 1. 把 this.handleClick 拿过来赋值给了 onClick 这个属性 */}
        {/* 2. 当咱们点击按钮的时候,React 内部会直接调用 onClick 这个属性,而直接调用类中的方法里面的 this 指向就是 undefined */}
        <button onClick={this.handleClick}>+1</button>
      </div>
    )
  }
}

此时,处理函数handleClick中打印的this 是===> undefined

解决方案:

方法 1

高阶函数:通过 this 来直接调用 handleClick 并 返回箭头函数。

🧐 柯里化:通过函数调用继续返回函数的形式,实现多次接收参数最后统一处理的函数编码形式。

handleClick() {
// 返回一个箭头函数
        // 这里的 this 指向是什么?那就看是谁调用的!
        return () => {
            console.log(this) // App {…}
            console.log(this.state.count)
        }
    }
     render() {
        return (
            <div>
                <h2>计数器:{this.state.count}</h2>
          // 通过 this 来直接调用 handleClick    
               <button onClick {this.handleClick()}>+1</button>
            </div>
        )
    }

方法 2

包裹一层箭头函数。 

由于箭头函数中的 this 指向“外部”,即 render 函数,而 render 函数中的 this 正是组件实例。

(由于是在同一个案例,下面就只展示需要修改的代码部分)

   
  handleClick() { console.log(this.state.count) }
 
  <button onClick={() => this.handleClick()}>+1</button>

方法 3

使用 bind。指定this指向 bind()第一个参数就是箭头函数this的指向。render 函数中的 this 正是组件实例

 handleClick() { console.log(this.state.count) }
 
    <button onClick={() => this.handleClick.bind(this)}>+1</button>

方法 4

通过赋值语句往实例上面添加一个箭头函数。

handleClick=()=> { console.log(this.state.count) }
 
<button onClick={ this.handleClick }>+1</button>

方法 5

在构造函数中再创建一个实例方法,和原型方法公用一个函数体。

再使用 bind。

constructor() {
        super()
this.handleClick = this.handleClick.bind(this)
    }
    handleClick() {
        console.log(this.state.count)
    }
    
  <button onClick={ this.handleClick }>+1</button>

  • 7
    点赞
  • 7
    收藏
    觉得还不错? 一键收藏
  • 2
    评论
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值