// 是react 内部监听到了 你点击了, 然后对 函数进行了一个回调,react 内部 并且给 这个函数的this 更改为 undefined
class Hello extends React.Component {
state = {
count: 0,
}
handleSum() {
// 事件处理程序中的 this 是 undefined
// 这个方法其实是 react 内部调用 , 内部调用的时候,没有 正确绑定 this
// 是react 内部监听到了 你点击了, 然后对 函数进行了一个回调,react 内部 并且给 这个函数的this 更改为 undefined
}
render() {
return (
<div>
<h1>计数器: {this.state.count}</h1>
<button onClick={this.handleSum}>+1</button>
</div>
)
}
}
解决方法
1、箭头函数方法
<button onClick={() => { this.handleSum() }}>+1</button>
class Hello extends React.Component {
state = {
count: 0,
}
handleSum() {
// 事件处理程序中的 this 是 undefined
this.setState({
// 要修改那个数据,就把那个数据放进来就可以
count: this.state.count + 1
})
}
render() {
return (
<div>
<h1>计数器: {this.state.count}</h1>
<button onClick={() => { this.handleSum() }}>+1</button>
</div>
)
}
}
2、Function.prototype.bind()
class Hello extends React.Component {
constructor() {
super()
this.handleSum = this.handleSum.bind(this)
}
state = {
count: 0,
}
handleSum() {
// 事件处理程序中的 this 是 undefined
this.setState({
// 要修改那个数据,就把那个数据放进来就可以
count: this.state.count + 1
})
}
render() {
return (
<div>
<h1>计数器: {this.state.count}</h1>
{/* <button onClick={() => { this.handleSum() }}>+1</button> */}
// 第一种
<button onClick={this.handleSum}>+1</button>
// 也可以不用再 constructor 中调用,直接 onClick={this.handleSum.bind(this)}
</div>
)
}
}
3、实例方法
class Hello extends React.Component {
state = {
count: 0,
}
handleSum = () => {
// 事件处理程序中的 this 是 undefined
this.setState({
// 要修改那个数据,就把那个数据放进来就可以
count: this.state.count + 1
})
}
render() {
return (
<div>
<h1>计数器: {this.state.count}</h1>
<button onClick={this.handleSum}>+1</button>
</div>
)
}
}