javascript - 更改 Material-UI 的纸张颜色
我正在使用 material-ui 库开发一个 React 项目。我目前正在尝试添加一个抽屉组件,这对我来说工作正常。然而,我正在尝试更改此抽屉的背景颜色。我听说实现这一点的方法是通过更改抽屉的纸张颜色。我已经尝试在我的 CSS 对象中添加以下标签:
const styles = theme => ({
background:"BLUE"
然后我在渲染函数中使用 classNames 库引用这个对象:
render(){
const { classes } = this.props;
return(
<div className={styles.root}>
<CssBaseline />
<Drawer
variant="permanent"
className={classNames(classes.drawer, {
[classes.drawerOpen]: this.state.open,
[classes.drawerClose]: !this.state.open
})}
classes = {{
paper: classNames({
background:classes.background,
[classes.drawerOpen]: this.state.open,
[classes.drawerClose]: !this.state.open
})
}}
然而,当我在本地主机上运行这个时,纸张仍然是普通的白色。我是不是对 classNames 库有什么误解,或者这是 paper 标签的一个特殊情况?提前感谢,如果需要我提供更多信息,请告诉我。
答案#1
你在问题中显示的代码里有几个问题。
对于你的风格,你需要类似以下的东西:
const styles = theme => ({
drawerPaper: { background: "blue" }
});
在这种情况下,“drawerPaper”是我的类名的键,然后右边的对象包含该类的CSS属性。当传入withStyles时,这将生成如下的CSS:
<style>
.classname-generated-for-drawerPaper-key: {
background: blue;
}
</style>
你有一个类名为“background”的键,其 CSS 属性字符串为“BLUE”,最终会得到如下 CSS:
<style>
.classname-generated-for-background-key: {
0: B;
1: L;
2: U;
3: E;
}
</style>
当然,这不是有效的 CSS,对论文没有任何影响。
第二个问题在于你如何指定这些类:
classes = {{
paper: classNames({
background:classes.background,
[classes.drawerOpen]: this.state.open,
[classes.drawerClose]: !this.state.open
})
}}
当你将一个对象传递给 classNames 时,对象的键是类名,而关联的值决定(基于其是否为假值或真值)该类名是否应被包含。按照你使用的语法,classes.background 将始终为真,这意味着类“background”(而不是 classes.background 中生成的类名)将被包含,这不会有任何效果,因为“background”类尚未定义。
你应该这样做:
classes = {{
paper: classNames(classes.drawerPaper, {
[classes.drawerOpen]: this.state.open,
[classes.drawerClose]: !this.state.open
})
}}
它将无条件地包含 classes.drawerPaper。
这是一个 Drawer 演示的修改版本,但抽屉的背景颜色改为蓝色:https://codesandbox.io/s/wqlwyk7p4l
答案#2
如果您使用全局 theme=createTheme(,背景纸张的颜色可以按如下方式设置
const theme = createTheme({
palette: {
{
primary: colors.blue,
background: {
default: colors.grey[50],
paper: colors.common.white,
},
// ...
