【问题标题】:How do you close the material UI context menu, without displaying the default context menu?如何在不显示默认上下文菜单的情况下关闭材质 UI 上下文菜单?
【发布时间】:2020-08-10 20:34:10
【问题描述】:

我正在尝试使用材质 UI 菜单在 div 上显示上下文菜单,如 https://material-ui.com/components/menus/#context-menu

我可以右键单击它并显示它。

但是,material-ui 上下文菜单在显示时会在菜单后面注入一个覆盖整个屏幕的透明 div。这意味着该元素会拦截任何进一步的点击。似乎此元素会在检测到左键单击时关闭菜单,但如果您右键单击页面上的任何其他位置(包括与上下文菜单无关的位置),它将移动并继续显示相同的上下文菜单

有没有办法在没有这个透明 div 的情况下显示菜单,这会从我的页面中移除控制?

您可以在示例中看到此操作:https://material-ui.com/components/menus/#context-menu 右键单击文本,然后右键单击其他任何位置(菜单仍然显示),您可以触发菜单出现在整个页面上,甚至在菜单选项没有意义的应用栏中。

【问题讨论】:

  • 你能分享你的代码吗?我面临同样的问题,发现即使Menu 附加到document.body,当右键单击叠加层时,onContextMenu 回调仍然会被触发。
  • 我找到的解决方案是使用onContextMenu 回调在元素外渲染Menu,但仍然不是很好。

标签: reactjs material-ui


【解决方案1】:

我试着这样做:

export default function MenuPopupState() {
  return (
    <PopupState variant="popover" popupId="demo-popup-menu">
      {popupState => {
        const menuProps = bindMenu(popupState);
        return (
          <React.Fragment>
            <Button
              variant="contained"
              color="primary"
              {...bindTrigger(popupState)}
            >
              Open Menu
            </Button>
            <Menu
              {...menuProps}
              onContextMenu={event => {
                event.preventDefault();
              }}
              onMouseDown={e => {
                menuProps.onClose();
              }}
            >
              <MenuItem onClick={popupState.close}>Cake</MenuItem>
              <MenuItem onClick={popupState.close}>Death</MenuItem>
            </Menu>
          </React.Fragment>
        );
      }}
    </PopupState>
  );
}

https://codesandbox.io/s/material-demo-szpbr?file=/demo.js

【讨论】:

  • 这如何回答这个问题? OP 正在使用onContextMenu() 来显示菜单。
猜你喜欢
  • 2021-04-18
  • 2012-05-06
  • 2019-11-21
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多