javascript - 更改 Material-UI 的紙張顏色
我正在使用 material-ui 庫開發一個 React 項目。我目前正嘗試添加一個抽屜,對我來說它運作正常。然而,我正在嘗試更改這個抽屜的背景顏色。我聽說更改的方法是修改抽屜的 paper 顏色。我已經嘗試將以下標籤添加到我的 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>
你有一個 class 名稱為 "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。
這裡是一個抽屜示範的修改版本,但抽屜的背景顏色改為藍色: https://codesandbox.io/s/wqlwyk7p4l
答案#2
如果你使用全域 theme=createTheme( 背景紙的顏色可以如下設定
const theme = createTheme({
palette: {
{
primary: colors.blue,
background: {
default: colors.grey[50],
paper: colors.common.white,
},
// ...
