首页 > 解决方案 > [tag][React.js] 孩子展示道具未定义

问题描述

我刚开始学习 React js,并且正在关注 youtube 上的 mosh 教程。我很肯定我做了他所做的,但我的道具说未定义。

counters.jsx 中的“值”是可访问的,但是当我尝试获取 id 时,它显示未定义。这是我在控制台中得到的输出:“ Event handler called! undefined ”

计数器.jsx

    import React, { Component } from "react";
import Counter from "./counter";

class Counters extends Component {
  state = {
    counters: [
      { id: 1, value: 0 },
      { id: 2, value: 0 },
      { id: 3, value: 0 },
      { id: 4, value: 0 },
    ],
  };

  handleDelete = (counterID) => {
    console.log("Event handler called!", counterID);
  };

  render() {
    return (
      <div>
        {this.state.counters.map((counter) => (
          <Counter
            key={counter.id}
            onDelete={this.handleDelete}
            value={counter.value}
          />
        ))}
      </div>
    );
  }
}

export default Counters;

计数器.jsx

    import React, { Component } from "react";

class Counter extends Component {
  state = {
    value: this.props.value,
  };

  // constructor() {
  //   super();
  //   this.handleIncrement = this.handleIncrement.bind(this);
  // }

  handleIncrement = () => {
    this.setState({ value: this.state.value + 1 });
  };

  render() {
    return (
      <div>
        <span className={this.getBadgeClasse()}>{this.formatCount()}</span>
        <button
          onClick={() => this.handleIncrement(this.state.product)}
          className="btn btn-secondary btn-sm"
        >
          Increment
        </button>
        <button
          onClick={() => this.props.onDelete(this.props.id)}
          className="btn btn-danger btn-sm m2"
        >
          Delete
        </button>
      </div>
    );
  }

  getBadgeClasse() {
    let classes = "badge m-2 badge-";
    classes += this.state.value === 0 ? "warning" : "primary";
    return classes;
  }

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

export default Counter;

谢谢你

标签: javascriptreactjs

解决方案


在 te Counters.jsx 中,您不传递 id 道具。你必须这样:

{this.state.counters.map((counter) => (
      <Counter
        key={counter.id}
        id={counter.id}
        onDelete={this.handleDelete}
        value={counter.value}
      />
    ))}

推荐阅读