首页 > 解决方案 > Material UI AppBar 不使用主题颜色

问题描述

我正在使用 Material UI v4.7.0。

我创建了一个使用createMuiTheme()主要和次要自定义颜色集的主题(见下文)。

我有一个 AppBar(见下文)。当我color将此设置为默认值并切换主题时,它只会在黑白之间变化!

如果我设置color="primary",它只显示main原色。如果我在主调色板中指定lightdark颜色,即使是这种情况(这就是我知道主题正确导入的方式)。

它只是不会因主题而改变!

不仅如此,body 标签和 Paper 组件上的背景颜色也只有黑色或白色阴影(取决于主题)。

文档(https://material-ui.com/customization/palette/)绝对没用!

有人可以帮助我如何为我的应用程序设置主题并让 MUI实际使用它吗?

这是 NavBar 代码(假设导入都在那里,它们是):

const useStyles = makeStyles(theme => ({
    root: {
        flexGrow: 1,
    },
    logo: {
        height: getToolbarLogoHeight()
    },
    menuButton: {
        marginRight: theme.spacing(2),
        [theme.breakpoints.up('sm')]: {
            display: 'none',
        },
    }
}));

const NavBar = () => {
    const theme = useTheme();

    const { isAuthenticated } = useContext(AuthContext);
    const classes = useStyles();
    const Logo = theme.palette.type === 'light' ? LogoLight : LogoDark;

    console.log(theme);

    return (
        <AppBar position="sticky" color="default" className={classes.root}>
            <Toolbar>
                <IconButton className={classes.menuButton}>
                    <FontAwesomeIcon icon={faBars}/>
                </IconButton>

                <Link to="/" style={{ flexGrow: 1 }}>
                    <img alt="logo" src={Logo} className={classes.logo}/>
                </Link>

                {
                    isAuthenticated &&
                    <TopLinks/>
                }
            </Toolbar>
        </AppBar>
    );
};

export default NavBar;

这是我的主题:

export const theme = createMuiTheme({
    palette: {
        primary: {
            main: '#2c3c52'
        },
        secondary: {
            main: '#94c93d'
        },
        type: 'dark'
    }
});

export const getToolbarLogoHeight = () => {
    return theme.mixins.toolbar.minHeight - 10;
};

export default theme;

标签: javascriptreactjsmaterial-ui

解决方案


我认为您需要制作自己的 AppBar 组件。我正在使用组件样式而不是钩子样式来编写此内容。

styles你需要

const styles = theme => ({
  lightMode: {
    backgroundColor: theme.palette.primary.light,
    color: theme.palette.primary.contrastText,
  }
  darkMode: {
    backgroundColor: theme.palette.primary.dark,
    color: theme.palette.primary.contrastText,
  }
});

withTheme然后用hoc包装你的 AppBar ,这样你就可以theme在 this.props 中访问了;然后在render()

const { theme } = this.props;
return (
  <AppBarFromMui
    className={clsx(
      [classes.lightMode]: theme.palette.type ==='light',
      [classes.darkMode]: theme.palette.type ==='dark',
    )}
  >
    {children or something}
  </AppBarFromMui>

推荐阅读