如何更改Material-UI AppBar 的浅色和深色主题颜色?

How to Change Light and Dark Theme Colors for Material-UI AppBar?

我对 React 还不是很深入...

AppBar 的样式像一个我不喜欢的按钮。

所以我想改变它的颜色,但也让它工作切换明暗方案。

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

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

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

不过,MuiTypography 有效。 (正如我在这里看到的 https://material-ui.com/customization/default-theme/ 没有 AppBar 只有排版。)

如何让 AppBar 使用 primary/secondary 以外的其他颜色,同时与内置的明暗主题机制保持同步?

再见,如果你想切换主题(例如从深色主题到浅色主题),你可以使用 primarysecondary 颜色(之前在 theme 对象中定义)。

所以让我们以我制作的 this codesandbox 为例:

  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 props (themeSelected) 中放置了一个状态变量。

好吧,现在我只创建了一个简单的 IconButton,带有 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,您可以更改颜色主题:

原色主题

二次色主题

编辑

经过您的解释,我了解到您希望 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
    }
  }

我更新了我的 codesandbox 示例。