暗模式存储在本地存储中 React with Material-UI

Darkmode Store in local storage React with Material-UI

暗模式的值如何存储到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

以下是如何设置和读取 LocalStorage 的示例:

import React, {useState, useEffect} from 'react';

export default function App() {
  const [theme, setTheme] = useState("light");

  useEffect(() => {
    setTheme(localStorage.getItem("theme"));
  }, []);

  const handleClick = theme => {
    localStorage.setItem("theme", theme);
    setTheme(theme);
  };

  return (
    <div className="App">
      <h1>Selected theme: {theme}</h1>
      <button onClick={() => handleClick("light")}>Light</button>
      <button onClick={() => handleClick("dark")}>Dark</button>
    </div>
  );
}
const [darkTheme, setDarkTheme] = useState(true);
const theme = createMuiTheme({
palette: {
  type: darkTheme ? "dark" : "light"
 }
})


useEffect(() => {
  const themeType = localStorage.getItem("dark") || "dark";
  if (themeType != "dark") {
    setDarkTheme(false);
  }
}, []);

const changeTheme = () => {
  localStorage.setItem("dark", darkTheme ? "light" : "dark");
  setDarkTheme(!darkTheme);
};

return (
    <div className="App">
        <p>Selected theme: " {theme} "</p>
        <button onClick={changeTheme}>toggle theme</button>
    </div>
);