this.handleClick 与 this.handleClick()

Kir*_*ran 2 reactjs

我有两个例子。在第一个示例中,我在 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>
 );
 } 
Run Code Online (Sandbox Code Playgroud)

Ali*_*Ali 6

this.handleClick()这将调用该方法并返回它的返回值,而this.handleClick它只是方法引用

在你的代码中

<button onClick={this.handleClick()} > Click here </button>
Run Code Online (Sandbox Code Playgroud)

你做的onClick等于什么this.handleClick()返回而这什么都没有

<button onClick={this.handleClick} > Click here </button>
Run Code Online (Sandbox Code Playgroud)

将使 onClick 参考this.handleClick方法


结帐这个例子

<button onClick={this.handleClick()} > Click here </button>
Run Code Online (Sandbox Code Playgroud)

日志记录foo()将等于 5 但日志记录foo将等于它自己的功能