gpt4 book ai didi

javascript - 使用 .map (Javascript/React) 获取要在数组中删除的元素的索引

转载 作者:行者123 更新时间:2023-12-01 01:28:19 25 4
gpt4 key购买 nike

我有一系列成分想要在我的 React 应用程序中显示为列表。与每个项目关联的是一个 Delete 按钮,单击该按钮时,将从数组中删除该特定元素并使用更新后的数组重新渲染。

有没有办法找到元素的索引并将其传递给handleDelete()函数?

或者是循环遍历所有元素以查找和删除的唯一方法?

handleDelete(id) {
//use id to remove element from the array
//setState of newly filtered array
}


render() {
var ingredients = ["chicken", "rice"]
return (

<ul className="pantry">
{
ingredients.map((ingred, index) => {
return <li key={ingred.index}><button onClick={this.handleDelete.bind(this, ingred.index)}>Delete</button>{ ingred }</li>
})
}
</ul>

);
}

最佳答案

看来你已经差不多完成了。您只需要在方法中创建一个闭包并实际返回回调函数。您还需要将成分存储在状态中。 (我还稍微清理了代码。)

constructor(props) {
super(props);

this.state = {
ingredients: ["chicken", "rice"],
};

this.handleDelete = this.handleDelete.bind(this);
}

handleDelete(indexToDelete) {
//use id to remove element from the array
//setState of newly filtered array
return (event) => {
this.setState((currentState) => {
const currentIngredients = currentState.ingredients;

return {
ingredients: currentIngredients.slice(0, indexToDelete - 1).concat(currentIngredients.slice(i, currentIngredients.length)),
};
});
};
}

renderIngredient(ingredient, index) {
return (
<li key={ingred}>
<button onClick={this.handleDelete(index)}>
Delete
</button>
{ingredient}
</li>
);
}

render() {
return (
<ul className="pantry">
{
this.state.ingredients.map(this.renderIngredient)
}
</ul>
);
}

关于javascript - 使用 .map (Javascript/React) 获取要在数组中删除的元素的索引,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53549283/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com