首页 > 解决方案 > Javascript 对象 ID 字段未传递给事件处理程序

问题描述

我有一个包含两个组件的反应应用程序,计数器和计数器,其中计数器组件的状态对象包含一个对象数组,每个对象代表一个计数器。

在 Counters 组件的实际 jsx 代码中,counters 数组中的项目正在呈现,每个项目都包含一个删除按钮,可以删除每个单独的计数器。现在,我有一个箭头函数来处理设置为正在呈现的 Counter 标签中的属性。在 Counter 组件中,删除按钮中有一个 onCLick 事件,该事件将被单击的 Counter 的 id 作为参数。

出于某种原因,删除不起作用,当我在控制台记录已单击的计数器的 id 时,会打印 undefined。什么可能导致无法从 Counter 组件中读取 id 属性?

相关代码如下:

计数器组件:

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


  render() {
    console.log(this.props);
    return (
      <div>
        {this.props.children}
        <span className={this.getBadgeClasses()}>{this.formatCount()}</span>
        <button
          onClick={() => this.handleIncrement({ id: 1 })}
          className="btn btn-sercondary btn-sm"
        >
          Increment
        </button>
        <button
          onClick={() => this.props.onDelete(this.props.id)}
          className="btn btn-danger btn-sm m-2"
        >
          Delete
        </button>
      </div>
    );
  }

计数器组件:

import Counter from "./counter";

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

  handleDelete = counterId => {
    console.log("Event Handler Called", counterId);
    const counters = this.state.counters.filter(c => c.id !== counterId);
    this.setState({ counters });
  };
  render() {
    return (
      <div>
        {this.state.counters.map(counter => (
          <Counter
            key={counter.id}
            onDelete={this.handleDelete}
            value={counter.value}
          />
        ))}
      </div>
    );
  }
}

标签: javascripthtmlreactjsjsx

解决方案


由于按钮需要它,因此您需要将 prop 传递idCouter组件的渲染功能;Couters<button onClick={() => this.props.onDelete(this.props.id)}

看这里

<Counter
   id={counter.id}
   key={counter.id}
   onDelete={this.handleDelete}
   value={counter.value}
/>

或者,您可以这样做

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

推荐阅读