我正在使用ReactJS的Material-UI 库构建一个应用程序。使用Theme Overrides API,我试图弄清楚如何全局设置组件的样式,但前提是它是另一个特定组件的子组件。
例如,我正在尝试MenuItem
在菜单中设置 s的背景/文本颜色<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>
的 a 覆盖它。<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>
使用道具将此样式传递给组件?由于这里的大多数样式都非常适合主题覆盖,这似乎是一种更好的方法,但也许我在滥用 API。
有关我上述代码的工作演示,请参阅:https ://codesandbox.io/s/3r9mkxq231
欢迎任何见解!谢谢!