使用css变量控制整体样式
1、首先创建一个hook,这个Hook主要是存储LocalStorage和给根节点添加或者删除class名
import React from "react";
function useAppearance() {
const isAuto = (val) => !val || val === "auto";
const getAppearance = (value) => {
let appearance = value || window.localStorage.getItem("appearance");
if (isAuto(appearance)) {
return "light";
}
return value;
};
const [state, setState] = React.useState(getAppearance);
const setStateWithLocalStorage = (value) => {
if (value === "dark") {
document.documentElement.classList.add("dark");
} else {
document.documentElement.classList.remove("dark");
}
window.localStorage.setItem("appearance", value);
setState(getAppearance(value));
};
return [state, setStateWithLocalStorage];
}
export default useAppearance;
2、css文件中在root中创建变量,在其它class中统一使用该变量
:root {
--background-color: red;
}
:root.dark {
--background-color: black;
}
.app {
font-family: sans-serif;
text-align: center;
}
.text {
color: var(--background-color);
}
网友评论