这段代码中的 handleClick 方法没有被绑定到 this,所以它在 render 方法中是不可用的。解决方法是在 handleClick 方法的定义中使用箭头函数或在构造函数中绑定 this。
例如:
class Example extends React.Component {
constructor(props) {
super(props);
this.handleClick = this.handleClick.bind(this);
}
handleClick() {
console.log('Button was clicked');
}
render() {
return (
<button onClick={this.handleClick}>
Click me
</button>
);
}
}