需求:点击+1按钮,计数器+1
import React, { Component } from 'react'
export default class App extends Component {
state = {
count: 0,
}
handleClick() {
//报错: Cannot read properties of undefined (reading 'state')
console.log(this.state.count)
}
render() {
return (
<div>
<h2>计数器:{this.state.count}</h2>
<button onClick={this.handleClick}>+1</button>
</div>
)
}
}
//报错: Cannot read properties of undefined (reading 'state')
分析原因:
-
render 函数是被组件实例调用的(可以通过修改 render 函数的名字来观察到),因此 render 函数中的 this 指向当前组件实例,所以在 render 函数中通过 this 实例访问 state 和 handleClick 没有问题。
-
但!
<button onClick={this.handleClick}>+1&l