如何更改Material-UI AppBar的明暗主题颜色?

问题描述

我还不太了解React ...

AppBar的样式类似于我不喜欢的按钮。

所以我想更改它的颜色,但还要使其在切换明暗方案时起作用。

[编辑] 我想为AppBar定义自己的颜色(不更改当前颜色)并将它们分别添加到明暗主题,因此当我切换主题时它会自动更改为明暗。 [/编辑]

使用ThemeProvider更改颜色已不起作用:

const theme = createMuiTheme({
    palette: {
        // type: 'dark'
    },overrides: {
        MuiTypography: {
            h1: {
                fontSize: 24,fontWeight: "normal"
            },h2: {
                fontSize: 22,},MuiAppBar: {
            background: 'white',borderBottom: "1px solid lightGray",}
    },

MuiTypography可以工作。 (正如我在这里https://material-ui.com/customization/default-theme/看到的那样,没有仅AppBar的版式。)

我如何告诉AppBar在与内置的明暗主题机制保持同步的同时使用主/辅助颜色以外的其他颜色?

解决方法

Ciao,如果要切换主题(例如,从深色主题切换为浅色主题),则可以使用primarysecondary颜色(先前在theme对象中定义)。

让我们以我制作的this代码和框为例:

  1. 我在主题中定义了2种颜色:

    const Theme = {
      palette: {
        primary: {
          main: "#000000"
        },secondary: {
          main: "#FFFFFF"
        }
      }
    };
    

在这种情况下,primary是我们的黑暗主题,secondary是我们的明亮主题。

  1. 我创建了MUI主题:

    const theme = createMuiTheme(Theme);
    
  2. 我将AppBar组件包装到ThemeProvider中,并创建了theme

    <ThemeProvider theme={theme}>
      <AppBar position="static" color={themeSelected}>
      ....
      </AppBar>
    </ThemeProvider>
    

正如您在AppBar组件上看到的那样,我在color道具(themeSelected)中放入了状态变量。

现在,我只创建了一个带有IconButton图标enter image description here的简单SwapHoriz,然后单击以更改状态变量themeSelected

...

const [themeSelected,setThemeSelected] = useState("primary"); // init as primary color

...

const changeTheme = () => {  // function to set state
   if (themeSelected === "primary") setThemeSelected("secondary");
   else setThemeSelected("primary");
};

...

<IconButton   //icon button with onClick handler
   className={classes.menuButton}
   color="inherit"
   aria-label="open drawer"
   onClick={() => {
      changeTheme();
   }}
>
   <SwapHoriz />
</IconButton>

就这样。现在,如果您单击SwapHoriz,则可以更改颜色主题:

原色主题

enter image description here

第二颜色主题

enter image description here

编辑

经过解释,我了解到您希望AppBar具有不同的颜色,并且当您更改主题时,AppBar应该采用该颜色。

在这种情况下,我知道的唯一方法是以这种方式覆盖AppBar的classes

<AppBar
   position="static"
   color={themeSelected}
   classes={{
      colorPrimary: classes.appbarpalette,colorSecondary: classes.appbarpalette
   }}
>

然后在您的makeStyles

...
appbarpalette: {
    "&.MuiAppBar-colorPrimary": {
      backgroundColor: purple[600] // instead of #000000 for primary now you have purple
    },"&.MuiAppBar-colorSecondary": {
      backgroundColor: green[600] // instead of #FFFFFF for secondary now you have green
    }
  }

我更新了我的codeandbox示例。