reactjs - 使用 Menu 映射多个 Card 组件
问题描述
我有一个项目数组,对于每个项目,我想显示一个 Card 组件。每张卡片都有一个弹出菜单。我无法打开要打开的特定单击菜单。我的代码一起打开所有菜单。这是代码片段。
第二个问题是我收到关于无法在按钮中包含按钮的警告。我使卡片标题可点击,然后我有菜单。为了避免警告,执行此操作的正确方法是什么?
const [anchorEl, setAnchorEl] = useState(null)
const handleMenuClick = (e) => {
e.stopPropagation()
setAnchorEl(e.currentTarget)
}
return (
{
props.items.map( (k, i) => (
<Card className={classes.root}>
<CardActionArea onClick={(e) => handleRedirect(e)}>
<MyMenu key={i} index={i} anchor={anchorEl} />
<CardHeader
action={
<IconButton id={i} aria-label="settings" onClick={handleMenuClick}>
<MoreVertIcon />
</IconButton>
}
title={k.title}
subheader={getTimestamp(k._id)}
/>
</CardActionArea>
我的菜单代码:
const MyMenu = ( { index, anchor } ) => {
const [anchorEl, setAnchorEl] = useState({})
useEffect(() => {
//setAnchorEl({[e.target.id]: anchor})
if (anchor!==null) {
if (index===anchor.id)
setAnchorEl({[index]: anchor})
}
}, [anchor, index])
const handleRedirect = (e) => {
e.stopPropagation()
//history.push('/item/'+ id)
}
const handleClose = (e) => {
e.stopPropagation()
setAnchorEl({[e.target.id]: null})
};
return (
<Menu
id={index}
anchorEl={anchorEl[index]}
open={Boolean(anchorEl[index])}
onClose={handleClose}
>
<MenuItem onClick={(e) => handleRedirect(e)}>Read</MenuItem>
<MenuItem onClick={(e) => handleRedirect(e)}>Edit</MenuItem>
</Menu>
)
}
解决方案
谢谢@桑迪。我能够通过将此代码移动到父组件来解决此问题
const [anchorEl, setAnchorEl] = useState({})
const handleMenuClick = (e) => {
e.stopPropagation()
setAnchorEl({[e.currentTarget.id]: e.currentTarget})
}
...
<IconButton id={i} onClick={handleMenuClick}>
推荐阅读
- sql-server - 检查 SQL SERVER 中是否存在日期和时间之间
- react-native - 如何从嵌套组件导航到其他组件反应原生?
- angular - 当Angular 5中的值为“否”时如何禁用按钮?
- python - 用于过滤重复项的二维“数组”或对象 python
- android - jump to custom view when phone rings
- jquery - DataTable 不是 Angular 中的函数
- twilio - Is it possible to do voice pitch shifting in Twilio group video?
- ios - 如何在类“子属性”上设置领域主键
- python - How to append multiple values in the same key in Python 3?
- javascript - 首次登录/导航后 Angular 6 样式无法正确加载