【问题标题】:Render menu exactly below materialUI appbar在 materialUI appbar 正下方渲染菜单
【发布时间】:2021-05-26 08:41:27
【问题描述】:

This 帖子展示了如何使用anchorEl 将菜单(弹出框)定向到其父项下方。但是我想知道是否有一种简单的方法可以将菜单偏移到应用栏下方恰好,同时保持与父按钮的水平对齐。

当前:

期望:

Sandbox

【问题讨论】:

  • 使用纯 CSS 绝对可行,但取决于您的元素层次结构。 IE。如果菜单是绝对定位或相对定位,并且父级(或者在这种情况下,我猜是应用栏)具有定义的“位置”属性。然后,您可以通过声明“底部:- 100%”或“转换:翻译”等量正数来移动菜单而不影响布局。两者都仅在不同方向上按自己的确切大小移动元素。 .. 最重要的部分是在父元素上设置一个位置属性。如果您想更改布局,请使用边距或填充

标签: jquery css reactjs material-ui


【解决方案1】:

好吧,我不确定这是不是最好的解决方案,但我最终不得不修改 JSX 元素树,创建一个样式化的包装器 div:

const appBarHeightCSS = css`
  min-height: 56px;
  @media (min-width: 0px) and (orientation: landscape) {
    min-height: 48px;
  }
  @media (min-width: 600px) {
    min-height: 64px;
  }
`;

const StyledButtonContainerDiv = styled.div`
  ${appBarHeightCSS}
  display: flex;
  justify-content: center;
  align-items: center;
  color: ${theme.palette.grey['400']};
`;

并通过 ref 传递 div 元素

const accountButtonDiv = React.useRef<HTMLDivElement | null>();

...

<StyledButtonContainerDiv ref={accountButtonDiv}>
  <ToolbarButton
    anchorRef={accountButtonDiv}
    Menu={AccountMenu}
    aria-label="account of current user"
    aria-controls="primary-search-account-menu"
    aria-haspopup="true"
   >
     <AccountCircle />
</ToolbarButton>

...

到自定义 ToolbarButton 组件

export default function ToolbarButton(props): JSX.Element {
  const { anchorRef, Menu, badgeContent, children, ...defaultProps } = props;

  const [anchorEl, setAnchorEl] = React.useState<null | HTMLElement>(null);

  const handleMenuOpen = () => {
    setAnchorEl(anchorRef.current);
  };

  return (
    <>
      <IconButton {...defaultProps} onClick={handleMenuOpen} color="inherit">
        <Badge badgeContent={badgeContent} color="secondary">
          {children}
        </Badge>
      </IconButton>
      <Menu anchorEl={anchorEl} setAnchorEl={setAnchorEl} />
    </>
  );
}

【讨论】:

    猜你喜欢
    • 2014-09-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-06-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多