【问题标题】:object didnt get passed to another method (React)对象没有被传递给另一个方法(反应)
【发布时间】:2022-01-05 01:39:17
【问题描述】:

我目前正在学习 react 并遵循视频教程,但我遇到了一个无法传递给另一个方法的对象,但是当我传递一个 ID 时它工作正常

方法如下

handleIncrement = (product) => {
    console.log(product);
    this.setState({ count: this.state.count + 1 });   
};

这是我尝试传递的方法

render() {
    return (
      <div>
        <span className={this.getBadgeClasses()}>{this.formatCount()}</span>
        <button
          onClick={this.handleIncrement({ id: 1 })}
          className="btn btn-secondary btn-sm"
        >
          Increment
        </button>
      </div>
    );

onClick={this.handleIncrement(product)} 上的产品错误为未定义

src\components\counter.jsx
  Line 19:47:  'product' is not defined  no-undef

但如果我使用onClick={() =&gt; this.handleIncrement({ id:1 })},它工作得很好,当我使用onClick={(product) =&gt; this.handleIncrement(product)}时也可以工作

【问题讨论】:

标签: javascript reactjs object methods


【解决方案1】:

你遇到的问题是

onClick={this.handleIncrement({ id: 1 })}

这是 ReactJS 新手通常的困惑,但这里是一般的经验法则,你有两种方法

  1. 如果您的函数不期望 parameter
funcWithoutParam = () => {
  console.log('hi')
}; 
onClick={this.funcWithoutParam}
  1. 如果您的函数需要 parameter
handleIncrement = (param) => {
  console.log(param)
}

onClick={() => this.handleIncrement({ id: 1 })}

【讨论】:

    【解决方案2】:

    onClick 事件处理程序必须是函数,而不是函数调用。这就是为什么您提供的示例 onClick={() =&gt; this.handleIncrement({ id:1 })} 可以工作,因为这是一个匿名函数,而您调用该函数的示例不起作用。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2012-03-01
      • 2015-08-26
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-09-15
      相关资源
      最近更新 更多