在下面的代码中,我试图在单击姓名旁边的删除按钮时从最终将成为组织结构图的人员中删除该人员。目前,什么也没有发生。我最接近的是当点击任何一个删除按钮时,所有 5 个人都被删除,但我只希望删除一个点击按钮的人。我觉得我犯的 JS 错误多于 React 错误。
See the full code sandbox here.
如有帮助,将不胜感激!
import React from "react";
import { Component } from "react";
const list = [
{
name: "Person 1",
phone: "123-4567",
itemId: 11
},
{
name: "Person 2",
phone: "123-4567",
itemId: 12
},
{
name: "Person 3",
phone: "123-4567",
itemId: 23
},
{
name: "Person 4",
phone: "123-4567",
itemId: 34
},
{
name: "Person 5",
phone: "123-4567",
itemId: 45
}
];
class Entry extends Component {
constructor(props) {
super(props);
this.state = {
list: list
};
this.handleClick = this.handleClick.bind(this);
}
handleClick(e) {
this.setState({
list: this.state.list.filter(function(person) {
return person !== e.target.value;
})
});
}
render() {
return (
<div>
{this.state.list.map(item =>
<tr key={item.itemId}>
<td>
{item.name}
</td>
<td>
{item.phone}
</td>
<td>
<a className="delete" onClick={this.handleClick} />
</td>
</tr>
)}
</div>
);
}
}
export default Entry;
最佳答案
你的点击事件没有值,可以传itemId:
onClick={() => this.handleClick(item.itemId)}
那么您的handleClick
应该如下所示:
handleClick(itemId) {
this.setState({
list: this.state.list.filter(function(person) {
return person.itemId !== itemId;
})
});
}
关于javascript - .setState() : Filtering a person from an array of objects on button click,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45714398/