我有一组颜色,选择一种颜色后,我希望能够删除onClick的所有选定颜色。我似乎无法删除我想要的那个,因为我已将其设置为 splice(index,1)。有什么建议吗?
state = {
colors: [],
name: [],
front: 'https://homepages.cae.wisc.edu/~ece533/images/boat.png',
back: 'https://homepages.cae.wisc.edu/~ece533/images/fruits.png'
};
deleteColor(color) {
let colors = [...this.state.colors.slice()]
const index = colors.findIndex(
x => x.value === color.value
)
colors.splice(index, 1)
this.setState({ colors: colors })
console.log('Deleted')
}
然后返回
<div
key={color.id}
onClick={e => {
e.stopPropagation()
e.preventDefault()
this.deleteColor(color)
}}
>
//something
</div>
我想删除onClick的任何元素。谢谢!
答案 0 :(得分:1)
您可以使一切变得简单。
deleteColor = (color) => (e) {
e.stopPropagation()
e.preventDefault()
this.setState({ colors: this.state.colors.filter((el) => el.value !== color.value) })
}
<div
key={color.id}
onClick={this.deleteColor(color)}
>
//something
</div>