簡體   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