dwa*_*wat 2 mui reactjs material-ui
我正在使用ReactJS的Material-UI 库构建一个应用程序。使用Theme Overrides API,我试图弄清楚如何全局设置组件样式,但前提是它是另一个特定组件的子组件。
例如,我试图MenuItem在<Select>菜单中设置s的背景/文本颜色,其中每个都<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;
Run Code Online (Sandbox Code Playgroud)
不幸的是,<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;
Run Code Online (Sandbox Code Playgroud)
所以,我的问题是:有没有办法只使用主题覆盖来做到这一点?或者我是否需要<ListItemText>使用 props有条件地将此样式传递给组件?由于这里的大多数样式都非常适合主题覆盖,这似乎是一种更好的方法,但也许我滥用了 API。
有关我上述代码的工作演示,请参阅:https : //codesandbox.io/s/3r9mkxq231
欢迎任何见解!谢谢!
实现这一点的一种方法是从祖先样式(在本例中为 MenuItem)定位后代 html 元素(例如 ListItemText 的跨度)。
以下是如何MenuItem.selected指定样式的示例:
selected: {
"&&": {
backgroundColor: "blue",
color: "white",
"&& span": {
color: "white"
}
},
"&&:hover": {
backgroundColor: "darkblue",
color: "white"
}
}
Run Code Online (Sandbox Code Playgroud)
完整代码(从您的 CodeSandbox 分叉)在这里:
| 归档时间: |
|
| 查看次数: |
14290 次 |
| 最近记录: |