You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

MUI Menu组件背景色异常:styled-components设置后页面大面积变色

如何正确使用styled-components为MUI Menu组件设置背景色?

你遇到的问题是因为MUI的Menu组件底层结构包含一个全屏的根容器(用于实现点击外部关闭菜单的遮罩逻辑),直接给Menu组件设置background-color会把这个全屏容器染成粉色,而非仅菜单列表区域。

解决这个问题有两种常用方式:

方式一:直接自定义MenuList组件

MUI Menu的实际菜单列表由MenuList组件渲染,我们可以直接对MenuList进行styled定制,然后通过Menu的MenuListProps指定使用这个自定义组件:

  1. 修改styles.js文件,创建styled的MenuList:
import styled from "styled-components";
import MenuList from "@mui/material/MenuList";

export const StyledMenuList = styled(MenuList)`
  width: 412px;
  background-color: pink;
`;
  1. 在组件中使用这个自定义MenuList:
import * as React from "react";
import Button from "@mui/material/Button";
import MenuItem from "@mui/material/MenuItem";
import Menu from "@mui/material/Menu";
import { StyledMenuList } from "./styles";

export default function BasicMenu() {
  const [anchorEl, setAnchorEl] = React.useState(null);
  const open = Boolean(anchorEl);
  const handleClick = (event) => {
    setAnchorEl(event.currentTarget);
  };
  const handleClose = () => {
    setAnchorEl(null);
  };

  return (
    <div>
      <Button
        id="basic-button"
        aria-controls={open ? "basic-menu" : undefined}
        aria-haspopup="true"
        aria-expanded={open ? "true" : undefined}
        onClick={handleClick}
      >
        Dashboard
      </Button>
      <Menu
        id="basic-menu"
        anchorEl={anchorEl}
        open={open}
        onClose={handleClose}
        MenuListProps={{
          "aria-labelledby": "basic-button",
          component: StyledMenuList
        }}
      >
        <MenuItem onClick={handleClose}>Profile</MenuItem>
        <MenuItem onClick={handleClose}>My account</MenuItem>
        <MenuItem onClick={handleClose}>Logout</MenuItem>
      </Menu>
    </div>
  );
}

方式二:使用styled-components嵌套选择器

利用MUI内置的CSS类名,在styled的Menu组件中直接选中内部的菜单列表元素:

修改styles.js文件:

import styled from "styled-components";
import Menu from "@mui/material/Menu";

export const MenuRaw = styled(Menu)`
  .MuiMenu-list {
    width: 412px;
    background-color: pink;
  }
`;

这样你的原有组件代码无需修改,样式会精准作用于菜单列表区域,而不会影响全屏的根容器。

内容的提问来源于stack exchange,提问作者Happy1234

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.03 17:10:39