如何根据 Material UI 的 github 标签选择器示例删除 Material UI 芯片元素
How to delete Material UI chip element based on Material UI's github label picker example
我正在玩 Material UI 自动完成组件的 github 标签选择器示例,并根据下面的沙箱对其进行了修改:
https://codesandbox.io/s/material-demo-hwi3l?file=/demo.js
自动完成工作正常。当我 select 列表中的公司名称时,它们在关闭后显示为芯片元素,而当我单独删除 select 它们时,它们也会被隐藏。但是,我无法弄清楚如何通过单击芯片的关闭按钮来删除单个元素。我无法弄清楚到底要在芯片的 onDelete 道具中放入什么?
{
value.map((company, index) => (
<Chip
label={company.name}
onDelete={(event, newValue) => {
//setPendingValue(company);
}}
color="primary"
className={classes.selectedCompanies}
/>
))
}
由于根据沙箱的芯片位于值数组内,我不确定如何在循环遍历它时从其中删除某些内容。任何帮助将不胜感激。
从数组中删除的一种方法是过滤每个迭代项不是可删除项的位置。这样做 returns 一个省略可删除项的新数组。所以在你的例子中:
删除处理程序:
const handleDelete = name => {
const newValue = value.filter(company => company.name !== name);
setValue(newValue);
};
芯片元素:
{value.map((company) => (
<Chip
key={company.name}
label={company.name}
onDelete={() => handleDelete(company.name)}
The codesandbox with the solution
请注意,在 React 中,您应该 include the iterated key in each list item。
我正在玩 Material UI 自动完成组件的 github 标签选择器示例,并根据下面的沙箱对其进行了修改: https://codesandbox.io/s/material-demo-hwi3l?file=/demo.js
自动完成工作正常。当我 select 列表中的公司名称时,它们在关闭后显示为芯片元素,而当我单独删除 select 它们时,它们也会被隐藏。但是,我无法弄清楚如何通过单击芯片的关闭按钮来删除单个元素。我无法弄清楚到底要在芯片的 onDelete 道具中放入什么?
{
value.map((company, index) => (
<Chip
label={company.name}
onDelete={(event, newValue) => {
//setPendingValue(company);
}}
color="primary"
className={classes.selectedCompanies}
/>
))
}
由于根据沙箱的芯片位于值数组内,我不确定如何在循环遍历它时从其中删除某些内容。任何帮助将不胜感激。
从数组中删除的一种方法是过滤每个迭代项不是可删除项的位置。这样做 returns 一个省略可删除项的新数组。所以在你的例子中:
删除处理程序:
const handleDelete = name => {
const newValue = value.filter(company => company.name !== name);
setValue(newValue);
};
芯片元素:
{value.map((company) => (
<Chip
key={company.name}
label={company.name}
onDelete={() => handleDelete(company.name)}
The codesandbox with the solution
请注意,在 React 中,您应该 include the iterated key in each list item。