材质UI AppBar不使用主题颜色

时间:2019-11-29 09:29:20

标签: javascript reactjs material-ui

我正在使用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;

2 个答案:

答案 0 :(得分:0)

我认为您需要制作自己的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来包装AppBar,以便您可以在this.props中访问theme;然后在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>

答案 1 :(得分:0)

我也偶然发现了这一点,不久后我意识到您确实必须为每种主题设置两种调色板颜色-一种用于白色,一种用于深色类型-为了使用Mui的自动渲染主题。

请参见Material UI doc's中的示例,然后在顶部的“暗/亮”按钮之间切换,以查看不同的 Main 颜色值。 GIF example

据我所知,它将始终使用 Main 值颜色,而(调色板颜色中的) Light / Dark (浅色/深色)的用途更多开发人员想要自定义特定组件或元素的解决方案,例如Mason Mao's answer。 因此,总结一下:深色/浅色调色板没有直接链接到深色/浅色主题