首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >如何根据本地存储设置梅主题?

如何根据本地存储设置梅主题?
EN

Stack Overflow用户
提问于 2022-10-24 21:10:30
回答 1查看 26关注 0票数 0

正如您在这里看到的,如果您遵循如何实现切换主题功能,则取决于mui的正式文档页面。一旦您重新加载该网站,主题将返回到轻主题。因此,如何根据localstorage**?** 设置mui主题

EN

回答 1

Stack Overflow用户

发布于 2022-10-24 23:54:32

一个简单的解决方案是做一些类似于文档这里的事情。

在您创建主题的地方,您想要制作这样的东西:

代码语言:javascript
复制
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>
  );
}
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/74186861

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档