【问题标题】:In my React application, I'm using a popover component from material ui. Hovering over the icon does not open the popover在我的 React 应用程序中,我使用了 Material ui 中的弹出框组件。将鼠标悬停在图标上不会打开弹出框
【发布时间】:2019-11-14 18:40:19
【问题描述】:

我无法弄清楚这一点。我已经实现了一个弹出框组件,当用户将鼠标悬停在“i”图标上时,应该打开一个弹出框,当用户将鼠标悬停在图标之外时,它应该关闭弹出框。我认为正在发生的事情是,当将鼠标悬停在图标上时,会不断调用 open 和 close 方法,因此看起来它从未被打开过。

我的组件:

export const InfoIconWrapper = styled(InfoIcon)(({ theme }) => ({
  color: fade(theme.palette.black, 0.3),
}));

export const GridWrapper = styled(Grid)(({ theme }) => ({
  pointerEvents: 'none',
  padding: theme.spacing(1),
}));

const DistributionLinePopover = ({ distributionLine }) => {
  const [anchorEl, setAnchorEl] = useState(null);

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

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

  const open = Boolean(anchorEl);
  const mouseOverPopover = 'mouse-over-popover';
  return (
    <Fragment>
      <Typography
        aria-owns={open ? mouseOverPopover : undefined}
        aria-haspopup="true"
        onMouseEnter={handlePopoverOpen}
        onMouseOut={handlePopoverClose}
      >
        <InfoIconWrapper fontSize="small" />
      </Typography>
      <Popover
        id={mouseOverPopover}
        open={open}
        anchorEl={anchorEl}
        anchorOrigin={{
          vertical: 'bottom',
          horizontal: 'left',
        }}
        transformOrigin={{
          vertical: 'top',
          horizontal: 'left',
        }}
        // onMouseOut={handlePopoverClose}
        disableRestoreFocus
      >
        <GridWrapper container>
         ...
        </GridWrapper>
      </Popover>
    </Fragment>
  );
};

如何修改此代码以使其按预期运行?最初我尝试将handlePopoverClose 传递给popover,但这使得只有当您将鼠标悬停在实际的popover 上而不是悬停在“i”图标之外时,popover 才会关闭。

【问题讨论】:

    标签: reactjs material-ui popover


    【解决方案1】:

    不要将anchorElem 存在作为开放布尔状态值的一部分。事实上,你根本不需要检查anchorElem。处理 DOM 元素引用时可能会出现竞争条件。

    我会将setAnchorEl 更改为setOpen,并在输入呼叫时将setOpen 更改为true。您可能希望使用 onClick 事件处理程序将“X”按钮设置为打开到 false。我认为从技术上讲,当在您悬停的元素上呈现新元素时,会为底层元素触发“鼠标移出”。见this

    According to the browser logic, the mouse cursor may be only over a single element at any time – the most nested one and top by z-index.

    【讨论】:

    • 好吧,我明白你在说什么。不幸的是,按照公司的要求进行设计是一项业务需求。 Material UI 有一个弹出代码 sn-p 你可以直接放入你的组件中。它工作得很好,不幸的是,这个团队再次不允许在反应中使用钩子,Material UI 中唯一的例子是带有钩子的代码 sn-p。应该有办法让它表现得像他们的一样(我不得不用一个样式化的组件替换钩子)但我想不通。
    【解决方案2】:

    好的,终于找到解决办法了。

    在 Popover 组件中,将其添加为 prop : style={{ pointerEvents: 'none' }} 并删除 onMouseOut。

    在 InfoIconWrapper 组件中,将此作为道具添加 onMouseLeave={handlePopoverClose}

    按预期工作:)

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-10-23
      • 1970-01-01
      • 2013-03-05
      • 1970-01-01
      • 2014-05-14
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多