目标
-
给按钮绑定点击事件
-
获取原来的数字
-
在原来数字的基础上 +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>