【问题标题】:ReactJS Material-UI how to fix a component on top of an anchored menuReactJS Material-UI 如何将组件固定在锚定菜单之上
【发布时间】:2021-05-26 12:43:18
【问题描述】:

我正在使用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 是一个有效的代码框。

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

【问题讨论】:

    标签: reactjs menu material-ui


    【解决方案1】:

    您可以使用position: fixed 来固定Test 2 的位置,但有一个限制,您需要定义menuTest 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>
    

    【讨论】:

      猜你喜欢
      • 2017-01-08
      • 2019-10-11
      • 1970-01-01
      • 1970-01-01
      • 2012-07-14
      • 2017-02-07
      • 2016-04-04
      • 2021-11-25
      • 2022-08-15
      相关资源
      最近更新 更多