我有一个有几个ListItems的列表,这是从数组中得到的,让我们称之为myCollection
。每个ListItem都有一个MenuIcon,它打开一个菜单,显示一个删除项目的选项。简化的代码如下所示:
<List>
<Menu
open={Boolean(anchorEl)}
anchorEl={anchorEl}
...>
<MenuItem onClick={() => handleDelete(⚡collectionItem)}>Delete</MenuItem>
</Menu>
{myCollection.map((collectionItem) => (
<ListItem secondaryAction={
<IconButton onClick={(e) => setAnchorEl(e.currentTarget)}>
<MoreVertIcon />
</IconButton>
}>
{collectionItem.name}
</ListItem>
)}
</List>
我的问题是,我需要知道选择了myCollection
中的哪一项才能将其传递给delete函数。但是,我没有从菜单中引用myCollection
数组中的当前myCollection
。将菜单移动到map函数中没有意义,因为会呈现多个菜单。我该如何解决这个问题?
发布于 2022-09-21 14:04:07
我通过给出IconButton
的自定义HTML数据属性来解决这个问题。
<IconButton data-collection-id={collection.id} onClick={...}>
...
</IconButton>
然后,在onClick函数中,我们可以使用event.currentTarget.getAttribute("data-collection-id")
检索它。
https://stackoverflow.com/questions/73294571
复制相似问题