我是 material-ui 和 React 的新手,我需要在循环中动态创建多个菜单。请找到以下代码片段:
state = {
anchorEl: null,
};
handleClick = event => {
this.setState({ anchorEl: event.currentTarget });
};
handleClose = () => {
this.setState({ anchorEl: null });
};
render() {
const { anchorEl } = this.state;
let items = _.map(results, (item, index) => {
return (
<ListItem
key={item.ID}
divider
>
<ListItemSecondaryAction>
<IconButton
aria-label="More"
aria-owns={anchorEl ? 'long-menu' : null}
aria-haspopup="true"
onClick={this.handleClick}
>
<MoreVertIcon />
</IconButton>
<Menu
id="long-menu"
anchorEl={anchorEl}
open={Boolean(anchorEl)}
onClose={this.handleClose}
PaperProps={{
style: {
maxHeight: 200,
width: 200,
},
}}
>
<MenuItem>
<IconButton onClick={() => this.props.delete(item.ID)} >
Delete entry<DeleteIcon />
</IconButton>
</MenuItem>
</Menu>
<ListItemSecondaryAction>
</ListItem>
)
})
return (
<Fragment>
<List>
{items}
</List>
</Fragment>
)
}
现在,使用上面的代码,菜单工作正常,用户界面也很好。但是每当我尝试通过单击菜单内的删除图标来删除条目时,总是删除最后一个条目,即 item.ID 传递最后一个元素的值,最后一个条目被删除。有没有一种方法可以为每个条目创建唯一的菜单项,并以确保删除正确的项目而不是始终删除最后一个的方式管理状态。注意:'results' 是任何动态加载的列表,'delete' 函数实现了删除相应条目的功能
提前致谢。