Material UI 主题覆盖:如何全局覆盖子样式?

2024-02-28

我正在构建一个应用程序材质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

欢迎任何见解!谢谢你!


实现此目的的一种方法是从祖先样式(本例中为 MenuItem)定位后代 html 元素(例如 ListItemText 的跨度)。

下面是一个示例,说明如何MenuItem.selected可以指定样式:

  selected: {
    "&&": {
      backgroundColor: "blue",
      color: "white",
      "&& span": {
        color: "white"
      }
    },
    "&&:hover": {
      backgroundColor: "darkblue",
      color: "white"
    }
  }

完整代码(从您的 CodeSandbox 分叉)位于此处:

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

Material UI 主题覆盖:如何全局覆盖子样式? 的相关文章

随机推荐