javascript - Material UI AppBar 不使用主题颜色
问题描述
我正在使用 Material UI v4.7.0。
我创建了一个使用createMuiTheme()
主要和次要自定义颜色集的主题(见下文)。
我有一个 AppBar(见下文)。当我color
将此设置为默认值并切换主题时,它只会在黑白之间变化!
如果我设置color="primary"
,它只显示main
原色。如果我在主调色板中指定light
和dark
颜色,即使是这种情况(这就是我知道主题正确导入的方式)。
它只是不会因主题而改变!
不仅如此,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;
解决方案
我认为您需要制作自己的 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>
推荐阅读
- llvm - 什么时候应该对 LLVM IR 使用“volatile”?
- php - 无法摆脱 PHP 回显中的额外空间
- apache - 从 URL 中删除首先使用 base64 编码然后在 .htaccess 文件中进行 urlencoded 的 GET 参数
- flutter - 交错的 BLoC 未按预期运行
- bootstrap-4 - 如何使锚标签在BS4中打开模型?
- django - 如何在 Jinja2 中启用“修剪”策略?
- groovy - 如何使用 groovy 检查特定的 yaml 结构
- java - 如何在 Spring Boot 中处理自定义 Content-Type 标头(MediaType)?
- amazon-web-services - Kubernetes 密钥和 AWS Secrets Manager - 将不同的 ARN 放入同一个文件?
- node.js - 如何使用 AJV 为 JSON 类型定义 (JTD) 指定最大或最小数量?