故事是,我应该能够将鲍勃,莎莉和杰克放进盒子里。我也可以从包装盒中取出。卸下后,将不留任何插槽。
people = ["Bob", "Sally", "Jack"]
我现在需要删除“鲍勃”。新的数组将是:
["Sally", "Jack"]
这是我的反应成分:
... getInitialState: function() { return{ people: [], } }, selectPeople(e){ this.setState({people: this.state.people.concat([e.target.value])}) }, removePeople(e){ var array = this.state.people; var index = array.indexOf(e.target.value); // Let's say it's Bob. delete array[index]; }, ...
在这里,我向您展示了一个最少的代码,因为它包含更多内容(onClick等)。关键部分是从数组中删除,删除,销毁“ Bob”,但removePeople()调用时不起作用。有任何想法吗?我一直在看这个,但由于使用React,所以我可能做错了。
removePeople()
要从数组中删除元素,只需执行以下操作:
array.splice(index, 1);
在您的情况下:
removePeople(e) { var array = [...this.state.people]; // make a separate copy of the array var index = array.indexOf(e.target.value) if (index !== -1) { array.splice(index, 1); this.setState({people: array}); } },