繁体   English   中英

变量未在 React-app 中定义 no-undef

[英]variable is not defined no-undef in React-app

我在这里关注Mosh Hamedani的教程创建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 行:'product' 未定义 no-undef

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

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

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

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

下面的代码对我有用:

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

按照相同的教程,我遇到了同样的问题。 我的理解是这里的“产品”是指事件。 就像 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>
    );
}

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

结果在控制台

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM