Javascript对象id字段未传递给事件处理程序

问题描述 投票:1回答:2

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

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

由于某种原因,删除不起作用,当我控制台记录已单击的计数器的ID时,将打印未定义。什么可能导致id属性不能从Counter组件中读取?

相关代码如下:

柜台组件:

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>
    );
  }
}
javascript html reactjs jsx
2个回答
1
投票

你需要在组件id的渲染函数中将prop Couter传递给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}
/>

0
投票

你有一个错字。

你应该在Component类的delete方法中使用this.props.key而不是this.props.id

© www.soinside.com 2019 - 2024. All rights reserved.