MUI Popover - 如何从鼠标位置开始转换?

Ryl*_*fer 2 material-ui

我希望材质 UIPopover在按下鼠标时打开/关闭,打开过渡从按下鼠标时鼠标的位置开始。我该怎么做呢?

e.s*_*leh 5

您需要设置anchorReferenceanchorPosition然后使用鼠标坐标作为锚点位置。因此,您需要使用状态来管理鼠标位置:

      const [mouseX, setMouseX] = useState();
      const [mouseY, setMouseY] = useState();
Run Code Online (Sandbox Code Playgroud)

然后在您的点击处理程序中设置状态:

    const handleClick = (event) => {
        setAnchorEl(event.currentTarget);
        setMouseX(event.clientX);
        setMouseY(event.clientY);
      }
Run Code Online (Sandbox Code Playgroud)

最后在你的 jsx 中使用鼠标位置anchorPosition

        return (
        <div>
          <Button aria-describedby={id} variant="contained" onClick={handleClick}>
            Open Popover
          </Button>
          <Popover
            id={id}
            anchorReference="anchorPosition"
            anchorPosition={{ top: mouseY, left: mouseX }}
            open={open}
            onClose={handleClose}
            anchorOrigin={{
              vertical: "top",
              horizontal: "left",
            }}
          >
            <Typography sx={{ p: 2 }}>The content of the Popover.</Typography>
          </Popover>
        </div>
      );
Run Code Online (Sandbox Code Playgroud)