【问题标题】:this.handleClick vs this.handleClick() [duplicate]this.handleClick 与 this.handleClick() [重复]
【发布时间】:2018-07-08 23:36:24
【问题描述】:

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

【问题讨论】:

  • 正确的方法是使用this.handleClick

标签: reactjs


【解决方案1】:

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

在你的代码中

<button onClick={this.handleClick()} > Click here </button>

你让onClick 等于this.handleClick() 返回的东西,而这什么都不是

<button onClick={this.handleClick} > Click here </button>

会让onClick引用this.handleClick方法


查看这个例子

function foo(){
    return 5;
}

console.log(foo());
console.log(foo);

记录 foo() 将等于 5,但记录 foo 将等于自行运行

【讨论】:

    猜你喜欢
    • 2019-10-02
    • 2011-10-26
    • 2013-02-24
    • 2020-10-30
    • 2013-07-16
    • 2012-10-22
    • 1970-01-01
    • 2010-09-21
    相关资源
    最近更新 更多