【问题标题】:identifying a component in react识别反应中的组件
【发布时间】:2019-09-01 10:36:05
【问题描述】:

我正在关注 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 行:“产品”未定义 无非定义

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

【问题讨论】:

  • 你从未在渲染方法中定义product

标签: javascript reactjs jsx


【解决方案1】:

这发生在您身上,因为您没有为您的函数提供输入。产品是您的输入变量而不是输入值。例如,如果运行如下代码,并检查您的浏览器控制台,您会看到它打印的值为 1

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() {

   const product=1;

    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;

希望对您有所帮助。如果它对你有用,请投票给我:)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-09-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多