之前学习了在同一组件下进行删除,直接调用this.state里的数据,进行filter筛选,然后更新状态即可。
但是现在counters数组是Counters的一部分,想要在Counter里通过删除按钮删除数据就不能直接使用上述方法了。为此,有了新的解决方法:
Counter组件发起事件onDelete,在Counters中实现handleDelete()方法。
首先,向Counters组件添加handleDelete方法,
// 删除按钮
handleDelete = countId => {
const counters = this.state.counters.filter(c => c.id !== countId);
this.setState({
counters
});
};
然后通过props给Counter组件传递一个方法的引用
<Counter
key={counter.id}
onDelete={this.handleDelete}
counter={counter}
/>
然后在Counter组件中调用该方法
<button
onClick={() => this.props.onDelete(this.props.counter.id)}
className="btn btn-danger btn-sm m-2"
>
Delete
</button>