如何将深色模式的值存储到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/