【问题标题】:How to get the name of the MenuItem on click using Menu and MenuItem from Material UI React如何使用 Material UI React 中的 Menu 和 MenuItem 在单击时获取 MenuItem 的名称
【发布时间】:2021-09-20 03:10:46
【问题描述】:

我在 React 中使用 MaterialUI 中的菜单和菜单项。我想在单击时打印菜单项的名称。

在console.log event.currentTarget 返回整个列表项:ListItem Image attached

在console.log event.currentTarget.dataset 返回DOMSTringMap。 WRT 我发现了一个类似的问题:Get value of MenuItem material ui 但是 DOMStringMap 的输出似乎无法使用。

检查 addMap 函数: 我想控制台记录菜单项的名称,即“ONE”。

import React from 'react';
import { useState } from 'react';
import {IconButton, Menu, MenuItem } from '@material-ui/core';


 const options = [
'ONE',
'TWO',
'THREE',
];

const ITEM_HEIGHT = 48;

export default function AdvanceOptionsMenu() {
 const [anchorEl, setAnchorEl] = useState(null);
 const open = Boolean(anchorEl);
 const [mapList, setMapList] = useState([]);

 const handleClick = (event) => {
   setAnchorEl(event.currentTarget);
 };

 const handleClose = () => {
  setAnchorEl(null);
 };

 const addMap = (event) => {
  **console.log(event.currentTarget)**
  handleClose();
 };

return (
<>
<div className="advance-menu">
  <IconButton
    aria-label="more"
    aria-controls="long-menu"
    aria-haspopup="true"
    onClick={handleClick}
  >
    <MoreVert />
  </IconButton>
  <Menu
    id="long-menu"
    anchorEl={anchorEl}
    keepMounted
    open={open}
    onClose={handleClose}
    PaperProps={{
      style: {
        maxHeight: ITEM_HEIGHT * 4.5,
        width: '20ch',
      },
    }}
  >
    {options.map((option) => (
      <MenuItem key={option} selected={option==="ONE"} onClick={addMap}>
        {option}
      </MenuItem>
    ))}
  </Menu>
  </div>
  {mapList}
  </>
);
}

【问题讨论】:

    标签: javascript reactjs


    【解决方案1】:

    您分享的问题链接,其中一个answers 建议使用event.target.innerText 来获取值。另一种方法可能是,您可以将值传递给MenuItem 中的onClick。我为这两个选项创建了一个demo。请查看。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2021-12-30
      • 2018-08-28
      • 2019-01-11
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多