之前学习了在同一组件下进行删除,直接调用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>

本文介绍了一种在React中从父组件Counters的state中删除子组件Counter数据的方法。通过在父组件中定义handleDelete方法,利用filter过滤出除要删除项外的所有数据,并更新state。子组件通过props接收onDelete方法,点击Delete按钮时触发,传入待删除项的id。
8158

被折叠的 条评论
为什么被折叠?



