在 MUI 中更改 Appbar backgroundColor

Change Appbar backgroundColor in MUI

MUI 将 Appbar 的默认颜色设置为原色,即蓝色。 如果我想直接使用 sx={{ background: 'white' }} 更改该颜色,那么我将失去深色主题的功能。换句话说,即使应用了 MUI 深色模式主题,白色背景也会卡住。这是一种不受欢迎的行为。

那么,如何在保持对 Mui 深色模式功能的支持的同时,以正确的方式更改 Appbar 的背景颜色?

首先检查用户对浅色或深色主题的偏好:

import useMediaQuery from '@mui/material/useMediaQuery';
const prefersDarkMode = useMediaQuery('(prefers-color-scheme: dark)')

然后你可以相应地设置AppBar的颜色:

const appBarColor = prefersDarkMode ? darkColor : lightColor
return <AppBar sx = {{ background: appBarColor }} />

您也可以选择检查 theme.palette.mode 的值来确定颜色。

useMediaQuery

prefers-color-scheme