ReactJS Material-UI 如何将组件固定在锚定菜单之上

ReactJS Material-UI how to fix a component on top of an anchored menu

我正在使用 Material-UI 并且我试图将一个固定组件放置在锚定菜单的顶部,也就是说我有一个按钮,我单击它然后会显示一个菜单。我需要将一个组件放在这个菜单的顶部并使其始终可见,如下所示:

但是当我向下滚动时,组件也会滚动。尽管滚动的位置我需要保持它可见。

这些是我一直在尝试的方法:

const renderMenu = () => {
    const items = [];
    for (let i = 0; i < 20; i += 1) {
      items.push(`Item ${i + 1}`);
    }
    return (
      <>
        {"Test one"}               <-----
        <Menu
          id="simple-menu"
          anchorEl={anchorEl}
          keepMounted
          PaperProps={{
            style: {
              maxHeight: "200px"
            }
          }}
          open={Boolean(anchorEl)}
          onClose={handleClose}
        >
          {"Test two"}             <-----
          {items.map((item) => (
            <MenuItem onClick={handleClose}>{item}</MenuItem>
          ))}
        </Menu>
      </>
    );
  };

  return (
    <>
      <Button
        aria-controls="simple-menu"
        aria-haspopup="true"
        onClick={handleClick}
        style={{ float: "right" }}
      >
        Click on me
      </Button>
      {anchorEl && renderMenu()}
    </>
  );

Test one 显示在弹出窗口外,Test two 滚动离开。 Here 是一个有效的 codesandbox。

知道如何解决这个问题吗?

您可以使用position: fixed来固定Test 2的位置,但是有一个限制,您需要定义menuTest 2的宽度。

这里是codesandbox,使用内联样式来快速演示:

https://codesandbox.io/s/material-demo-forked-6yz0l?file=/demo.js

<MenuItem // <-- use MenuItem to wrap the Test 2 to match the menu item css as much as possible
    style={{
        position: "fixed",  // fix the position to avoid it scrolling
        backgroundColor: "#ececec",
        zIndex: 1,          
        marginTop: "-8px",  // to align with original menu top margin
        width: "40%"        // need to have fix width. Otherwise, it will only follow content width
        borderRadius: "5px 5px 0px 0px"  // add the top corner border radius to match the menu style
    }}
    button={false} // to stop clicking effect
>
  {"Test two"}
</MenuItem>