Reactjs this.handleClick与this.handleClick()

Reactjs this.handleClick与this.handleClick(),reactjs,Reactjs,我有两个例子。在第一个示例中,我在JSX中使用了这个.handleClick(),但它不起作用。然而,在第二个例子中,我在JSX中使用了this.handleClick,它可以工作。我想,我缺少一些基本的东西 class MyComponent extends React.Component{ constructor(props) { super(props); this.state = {counter: 0}; this.handleClick = this.handleC

我有两个例子。在第一个示例中,我在JSX中使用了这个.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>
 );
 } 
类MyComponent扩展了React.Component{ 建造师(道具){ 超级(道具); this.state={counter:0}; this.handleClick=this.handleClick.bind(this); } handleClick(){ this.setState({counter:this.state.counter+this.props.increment}); } render(){ 返回( 当前计数器为{this.state.counter}

点击这里 ); } } 函数App(){ 返回( ); }
this.handleClick()
这将调用该方法并返回其返回值,而
this.handleClick
只调用方法引用

在代码中

<button onClick={this.handleClick()} > Click here </button>
将使onClick引用此.handleClick方法


请检查此示例

函数foo(){
返回5;
}
log(foo());

console.log(foo)正确的方法是使用
this.handleClick
<button onClick={this.handleClick} > Click here </button>