【问题标题】:Not able to fit the Menu width as same as the containers width using material-ui (mui-v5) and reactjs无法使用 material-ui (mui-v5) 和 reactjs 使菜单宽度与容器宽度相同
【发布时间】:2026-01-10 11:50:02
【问题描述】:

我试图创建一个宽度必须与Button 相同的菜单。但不知何故,Menu 的宽度没有按预期设置。仅出于试用目的,我还尝试将整个菜单放入 Grid Item 容器中并尝试将其放入其中。但即使这样也没有用。 我试过给absolute 样式,但仍然没有用。它曾经使它要么非常大要么非常小。

这是一个可以玩的代码。我重新创建了我所面临的相同问题并且可以编辑。

CustomButton Code

这个项目只有一个文件,其中包含所有基本代码。即:ButtonCustom.js。 请通过它,请给我一个相同的解决方案。我想让它保持响应,这就是我在项目中使用Grid 的原因。

谢谢!!

【问题讨论】:

    标签: reactjs react-hooks material-ui


    【解决方案1】:

    由于您已经将Button原生html元素保存在状态中(即anchorEl),您可以将菜单列表的宽度定义为按钮的宽度。

    只需一行代码即可完成:

        <Menu
          // other props here
          MenuListProps={{
             "aria-labelledby": "basic-button",
             sx: { width: anchorEl && anchorEl.offsetWidth } // <-- The line that does all
          }}
        >
    

    【讨论】:

    • 非常感谢!!!