正如您在这里看到的,如果您遵循如何实现切换主题功能,则取决于mui的正式文档页面。一旦您重新加载该网站,主题将返回到轻主题。因此,如何根据localstorage**?** 设置mui主题
发布于 2022-10-24 23:54:32
一个简单的解决方案是做一些类似于文档这里的事情。
在您创建主题的地方,您想要制作这样的东西:
const ColorModeContext = React.createContext({ toggleColorMode: () => {} });
export default function App() {
const [mode, setMode] = useState('light');
useEffect(() => {
// If there is a window
if (typeof window !== 'undefined')
// When the app loads, the mode is updated to the locally stored theme if it exists or else set to light
setMode(window.localStorage.getItem('theme') || 'light');
}, []);
const colorMode = useMemo(
() => ({
// The dark mode switch would invoke this method
toggleColorMode: () => {
const newMode = mode === 'light' ? 'dark' : 'light';
window.localStorage.setItem('theme', newMode);
setMode(newMode);
},
}),
[],
);
// Update the theme only if the mode changes
const theme = React.useMemo(() => createTheme({}), [mode]);
return (
<ColorModeContext.Provider value={colorMode}>
<ThemeProvider theme={theme}>
<Page />
</ThemeProvider>
</ColorModeContext.Provider>
);
}https://stackoverflow.com/questions/74186861
复制相似问题