首页 > 解决方案 > 使用 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>
  )
}

标签: reactjs

解决方案


谢谢@桑迪。我能够通过将此代码移动到父组件来解决此问题

  const [anchorEl, setAnchorEl] = useState({})

  const handleMenuClick = (e) => {
    e.stopPropagation()
    setAnchorEl({[e.currentTarget.id]: e.currentTarget})
  }

...

<IconButton id={i} onClick={handleMenuClick}>

推荐阅读