マテリアルの明るいテーマと暗いテーマの色を変更する方法-UIAppBar?
私はまだ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に指示するにはどうすればよいですか?
回答
チャオ、テーマを(たとえばダークテーマからライトテーマに)切り替えたい場合はprimary
、secondary
色(以前はtheme
オブジェクトで定義されていた)を使用できます。
それでは、私が作成したこのコードサンドボックスの例を見てみましょう。
テーマで2色を定義しました:
const Theme = { palette: { primary: { main: "#000000" }, secondary: { main: "#FFFFFF" } } };
この場合、primary
はダークテーマでsecondary
あり、ライトテーマです。
MUIテーマを作成しました:
const theme = createMuiTheme(Theme);
私はラップ
AppBar
にコンポーネントをThemeProvider
持つtheme
作成します:<ThemeProvider theme={theme}> <AppBar position="static" color={themeSelected}> .... </AppBar> </ThemeProvider>
AppBar
コンポーネントでわかるように、私は状態変数をcolor
小道具(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がその色を使用する必要があることを理解しました。
この場合、私が知っている唯一の方法は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の例を更新しました。