javascript - 深色模式存储在本地存储中 React with Material-UI

标签 javascript reactjs material-ui frontend themes

如何将深色模式的值存储到localStorage中?

我可以这样做吗?

你们能给我一些想法吗?

谢谢大家,

function App() {

  const [darkState, setDarkState] = useState("");
  const palletType = darkState ? "dark" : "light";
  const mainPrimaryColor = darkState ? blue[400] : blue[800];
  const mainSecondaryColor = darkState ? grey[800] : grey[100];

  const darkTheme = createMuiTheme({
    palette: {
      type: palletType,
      primary: {
        main: mainPrimaryColor,
      },
      secondary: {
        main: mainSecondaryColor,
      },
    },
  });
 function handleThemeChange() {
    setDarkState(!darkState);
  }
 return (
    <ThemeProvider theme={darkTheme}>
       <IconButton onClick={handleThemeChange()}>
            <Switch checked={darkState} />
        </IconButton>
    </ThemeProvider>
  );
}

最佳答案

要执行此操作:

  • 在 useEffect 中,我们查看 localStorage 中是否有内容并使用它
  • 当我们切换时,我们也会更新 localStorage

相关JS:

  useEffect(() => {
    const existingPreference = localStorage.getItem("darkState");
    if (existingPreference) {
     ( existingPreference === "light")
        ? setDarkState("light")
        : setDarkState("dark");
    } else {
      setDarkState("light");
      localStorage.setItem("darkState", "light");
    }
  }, []);

const handleThemeChange = () => {
    setSwitchState(switchState === true ? false : true);
    if (darkState === "light") {
      setDarkState("dark");
      setMainPrimaryColor(grey[400]);
      setMainSecondaryColor(blue[400]);
      localStorage.setItem("darkState", "dark");
    } else {
      setDarkState("light");
      setMainSecondaryColor(grey[400]);
      setMainPrimaryColor(blue[400]);
      localStorage.setItem("darkState", "light");
    }
  };

正在工作stackblitz

关于javascript - 深色模式存储在本地存储中 React with Material-UI,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63097218/

相关文章:

reactjs - 在 Material UI 主题中动态更改主色

css - 减小 Material UI 的组件大小

css - 如何更改 Griddle 中 Next/Prev 按钮的样式

javascript - OpenLayers 3不绘制多边形

javascript - 如何在 JavaScript 中生成键值反转对象?

javascript - 使用 Javascript 按下命令键时在新窗口中打开链接

javascript - 待办事项应用程序没有显示错误,但 src .js 文件不会显示

javascript - 允许在值绑定(bind) react 输入中使用减号(-)

javascript - 在 React Native 中制作一个可重用的组件?

javascript - 使用 supabase 计算 DISTINCT 值的出现次数