【发布时间】:2019-08-04 21:42:18
【问题描述】:
我有一个包含两个组件 Counters 和 Counter 的 react 应用程序,其中 Counters 组件的状态对象包含一个对象数组,每个对象代表一个 Counter。
在 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>
);
}
}
【问题讨论】:
标签: javascript html reactjs jsx