<分区>
我有两个例子。在第一个示例中,我在 JSX 中使用了 this.handleClick() 但它不起作用。但是,在第二个示例中,我在 JSX 中使用了 this.handleClick 并且它有效。我想,我缺少一些基础知识。
class MyComponent extends React.Component{
constructor(props) {
super(props);
this.state = {counter: 0};
this.handleClick = this.handleClick.bind(this);
}
handleClick() {
this.setState({counter: this.state.counter + this.props.increment});
}
render() {
return(
<div>
<p> Current counter is {this.state.counter} </p>
<button onClick={this.handleClick()} > Click here </button>
</div>
);
}
}
function App() {
return (
<div>
<MyComponent increment={5} />
</div>
);
}