【问题标题】:variable is not defined no-undef in React-app在 React-app 中未定义变量 no-undef
【发布时间】:2019-07-08 09:59:00
【问题描述】:

我正在关注 Mosh Hamedani 的教程 here 创建 react-app。

我完全按照他说的做了。

我正在尝试将一个名为 product 的参数传递给一个为 onClick 调用的函数 但是,我遇到了一个我没有找到太多信息的错误。

代码如下:

import React, { Component } from "react";

class Counter extends Component {
  state = {
    count: 0
  };

  formatCount() {
    return this.state.count === 0 ? "Zero" : this.state.count;
  }

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

  render() {
    return (
      <React.Fragment>
        <span className={this.formatSpan()}>{this.formatCount()}</span>
        <button
          onClick={() => this.handleIncrement(product)}
          className="btn btn-primary"
        >
          Increment
        </button>
      </React.Fragment>
    );
  }
}

export default Counter;

这是错误:

编译失败。

./src/components/counter.jsx 第 41 行:“产品”未定义 无非定义

搜索关键字以了解有关每个错误的更多信息。

【问题讨论】:

  • 在代码onClick={() =&gt; this.handleIncrement(product)}中没有定义变量product
  • {() =&gt; this.handleIncrement(product)} 产品未在此范围内定义
  • 好的。但是在他没有定义变量product的教程中它是如何工作的呢?
  • @Underoos 你找到修复了吗
  • 不。未找到。

标签: javascript reactjs parameters onclick react-component


【解决方案1】:

您将产品作为未定义的变量传递 以反逗号传递参数,否则声明它并赋值。

使用

onClick={() => this.handleIncrement("product")}

【讨论】:

    【解决方案2】:

    按照相同的教程,我遇到了同样的问题。我的理解是这里的“产品”是指事件。就像 H_R_S 建议的那样,使用以下代码:

    handleIncrement = (product) => {
        console.log(product);
        this.setState({count : this.state.count + 1});
    }
    
    render() {
        return (
            <React.Fragment>
                <span className={this.getBadgeClasses()}>{this.formatCount()}</span>
                <button onClick={(product) => this.handleIncrement(product)} className="btn btn-secondary btn-sm">Increment</button>
            </React.Fragment>
        );
    }
    

    您将能够在控制台中看到该事件:

    Result in console

    【讨论】:

      【解决方案3】:

      product 从未在您的组件中定义。因此没有定义。 您可以在组件状态中声明产品,或者将产品作为道具传递给组件。

      【讨论】:

        【解决方案4】:

        以下代码对我有用:

        onClick={(product) => this.handleIncrement(product)}
        

        【讨论】:

          猜你喜欢
          • 2020-12-21
          • 1970-01-01
          • 2019-11-10
          • 2019-10-05
          • 2018-03-18
          • 2022-01-08
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多