我正在构建一个应用程序材质UI库 https://material-ui.com/对于 ReactJS。使用主题覆盖 API https://material-ui.com/customization/overrides/#global-theme-override,我试图弄清楚如何全局设置组件的样式,但前提是它是另一个特定组件的子组件。
例如,我正在尝试设置背景/文本颜色MenuItem
里面有一个<Select>
菜单,其中每个<MenuItem>
包含一个<listItemText>
。这是我的组件:
import { MenuItem, Select, ListItemText } from '@material-ui/core';
import { MuiThemeProvider } from '@material-ui/core/styles';
import * as React from 'react';
import theme from './theme';
const MySelect = props => {
return (
<MuiThemeProvider theme={theme}>
<Select variant="standard" value="2" open>
<MenuItem value="1">
<ListItemText>One</ListItemText>
</MenuItem>
<MenuItem value="2">
<ListItemText>Two</ListItemText>
</MenuItem>
<MenuItem value="3">
<ListItemText>Three</ListItemText>
</MenuItem>
<MenuItem value="4">
<ListItemText>Four</ListItemText>
</MenuItem>
</Select>
</MuiThemeProvider>
);
};
export default MySelect;
不幸的是,将颜色应用到<MenuItem>
直接不起作用,因为<ListItemText>
用一个覆盖它<Typography>
有自己的着色集。这对于非悬停、非选定状态来说很好,但如果我设置“选定”样式MenuItem
为了有一个较暗的背景,我需要它有一个较浅的文本。
这是我的主题文件:
import { createMuiTheme, createStyles } from '@material-ui/core';
const myTheme = createMuiTheme({
overrides: {
MuiMenuItem: createStyles({
root: {
'&&:hover': {
backgroundColor: 'pink',
color: 'white'
}
},
selected: {
'&&': {
backgroundColor: 'blue',
color: 'white'
},
'&&:hover': {
backgroundColor: 'darkblue',
color: 'white'
}
}
}),
// How do I enforce this ONLY inside of MuiMenuItem and only for
// the selected variant of that?
MuiTypography: {
subheading: {
color: 'white'
}
}
}
});
export default myTheme;
所以,我的问题是:有没有办法只使用主题覆盖来做到这一点?或者我是否需要有条件地将这种样式传递到<ListItemText>
使用 props 的组件?由于这里的大部分样式都非常适合主题覆盖,这似乎是一个更好的方法,但也许我误用了 API。
有关我的上述代码的工作演示,请参阅:https://codesandbox.io/s/3r9mkxq231 https://codesandbox.io/s/3r9mkxq231
欢迎任何见解!谢谢你!