前端主题切换- sass 主题切换
sass + react 切换主题颜色
我们经常看到网页有主题切换功,如暗黑模式/白天模式,介绍通过scss变量来切换主题方案和常见的方案。
1. 定义主题颜色
定义主题颜色在全局样式中,在入口文件中引入全局样式。其他样式文件中var()来使用变量。当主题切换时,使用的样式就会变化。
// global.scss
html[data-theme="dark"] {
--primary-color: #ffffff;
--primary-background-color: rgba(14, 14, 14, 1);
--footer-background-color: rgba(36, 36, 36, 1);
--navbar-background-color: rgba(0, 0, 0, 0.5);
--secondary-color: rgba(255, 255, 255, 0.5);
--link-color: #34a8eb;
}
html[data-theme="light"] {
--primary-color: #333333;
--primary-background-color: rgba(255, 255, 255, 1);
--footer-background-color: #f4f5f5;
--navbar-background-color: rgba(255, 255, 255, 0.5);
--secondary-color: #666666;
--link-color: #0070f3;
}
// 其他文件中读取变量
.card{
line-height: 20px;
background-color: var(--primary-background-color);
color:var(--primary-color) ;
}
2. react中数据共享,保存主题数据
在react context中保存当前主题,切换时同时将主题存到localStorage中,当下次用户进入页面时,还是显示上次设置的主题样式。
//定义主题颜色枚举
export enum Themes {
dark = "dark",
light = "light",
}
interface ThemeContextOptions {
theme: Themes;
setTheme: (Themes: Themes) => void;
}
interface IProps {
children: JSX.Element;
}
const ThemeContext = createContext<ThemeContextOptions>(
{} as ThemeContextOptions
);
export const ThemeContextProvider = ({ children }: IProps): JSX.Element => {
const [theme, setTheme] = useState(Themes.light);
return (
<ThemeContext.Provider
value={{
theme,
setTheme: (currentTheme: Themes) => {
setTheme(currentTheme);
localStorage.setItem('theme',currentTheme)
document.getElementsByTagName("html")[0].dataset.theme = currentTheme;
},
}}
>
<div>{children}</div>
</ThemeContext.Provider>
);
};
在app中使用provider包裹子元素
export default function App({ Component, pageProps }: AppProps) {
return (
<ThemeContextProvider>
<Layout>
<Component
{...pageProps}
/>
</Layout>
</ThemeContextProvider>
);
}
小结
其他切换主题的方案:
- 多套css样式,切换link来加载不同的样式文件,来实现主题切换
- 类名切换来实现,同样加载多套样式。