Material UI主题配置:如何修改下拉菜单的背景颜色?
问题分析与解决
你的问题出在全局MuiList样式的优先级覆盖了MuiMenu内部List的样式。
你给MuiList-root设置了backgroundColor: '#525254',而MuiMenu组件内部默认使用MuiList渲染菜单选项列表,这个全局样式会直接作用在菜单里的List上,完全盖住你设置的MuiMenu-paper白色背景,最终显示的就是secondary主题色的背景。
修复方案
以下两种方式均可解决问题:
方式一:限制MuiList样式的作用范围
只给Drawer内的List应用深色背景,避免全局影响:
import { createTheme } from '@mui/material/styles'; const theme = createTheme({ palette: { primary: { main: '#F96300', }, secondary: { main: '#525254', }, }, components: { MuiDrawer: { styleOverrides: { paper: { backgroundColor: '#525254', color: '#FFF', // 将List样式移至Drawer内部,仅作用于Drawer里的List '& .MuiList-root': { backgroundColor: '#525254', '& .MuiListItem-root:hover': { backgroundColor: '#F96300', }, }, }, }, }, MuiMenu: { styleOverrides: { paper: { backgroundColor: '#FFF', }, list: { '& .MuiMenuItem-root:hover': { backgroundColor: '#F96300', color: '#FFF', }, }, }, }, }, }); export default theme;
方式二:给MuiMenu的List单独覆盖样式
保留全局MuiList样式,给MuiMenu内部List设置更高优先级的白色背景:
import { createTheme } from '@mui/material/styles'; const theme = createTheme({ palette: { primary: { main: '#F96300', }, secondary: { main: '#525254', }, }, components: { MuiDrawer: { styleOverrides: { paper: { backgroundColor: '#525254', color: '#FFF', }, }, }, MuiList: { styleOverrides: { root: { backgroundColor: '#525254', '& .MuiListItem-root:hover': { backgroundColor: '#F96300', }, }, }, }, MuiMenu: { styleOverrides: { paper: { backgroundColor: '#FFF', }, list: { // 覆盖全局MuiList的背景色 backgroundColor: '#FFF', '& .MuiMenuItem-root:hover': { backgroundColor: '#F96300', color: '#FFF', }, }, }, }, }, }); export default theme;
推荐第一种方式,样式作用范围更精准,不会影响其他场景下的MuiList组件。
内容的提问来源于stack exchange,提问作者Paul LeDuc
相关产品推荐
相关产品推荐

