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

标签 reactjs menu material-ui

我正在使用 Material-UI我正在尝试将一个固定组件放置在锚定菜单的顶部,也就是说我有一个按钮,我单击它然后显示一个菜单。我需要在此菜单上放置一个组件并使其始终可见,如下所示:
enter image description here
但是当我向下滚动时,组件也会滚动。尽管滚动的位置,我需要保持这个可见。
这些是我一直在尝试的方法:

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是一个工作的代码框。
关于如何解决这个问题的任何想法?

最佳答案

您可以使用 position: fixed修复Test 2的位置但是有一个限制,您需要定义 menu 的宽度和 Test 2 .
这是代码框,使用内联样式进行快速演示:
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>

关于ReactJS Material-UI 如何将组件固定在锚定菜单之上,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/67705137/

相关文章:

javascript - React 路由器问题 : React render two components in the same page

reactjs - Next.js 中的 Slug 不是整个文件名?

c++ - 使用 Composite Pattern 制作游戏菜单

html - 菜单列表项宽度拒绝更改?

javascript - 如何使用反引号将 react 元素插入数组

javascript - 分组和验证字段

reactjs - React.js + OpenCV.js ReferenceError:未定义cv

python - 使用 PyGTK 的右键单击菜单(上下文菜单)

javascript - 如何在 Material-UI 的 TextView 中选择元素后更改字体颜色

javascript - React 中的 TextField 内无法识别新行 '\n'