マテリアルの明るいテーマと暗いテーマの色を変更する方法-UIAppBar?

Aug 22 2020

私はまだReactにあまり深くは入っていません...

AppBarは、私が気に入らないボタンのようなスタイルになっています。

だから、色を変えたいだけでなく、明暗の切り替えも機能させたいです。

[編集] AppBarに独自の色を定義し(現在の色を変更せずに)、テーマを切り替えると自動的に明るい/暗いテーマに変更されるように、それぞれ明るい/暗いテーマに追加します。[/編集]

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に指示するにはどうすればよいですか?

回答

GiovanniEsposito Aug 22 2020 at 19:24

チャオ、テーマを(たとえばダークテーマからライトテーマに)切り替えたい場合はprimarysecondary色(以前はthemeオブジェクトで定義されていた)を使用できます。

それでは、私が作成したこのコードサンドボックスの例を見てみましょう。

  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)に入れました。

さてIconButtonSwapHorizアイコン付きのシンプルなものを作成し、

クリックすると状態変数を変更します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がその色を使用する必要があることを理解しました。

この場合、私が知っている唯一の方法はclasses、次の方法でAppBarのをオーバーライドすることです。

<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の例を更新しました。