You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

React中如何基于Session Storage值动态加载CSS文件

实现基于Session Storage的SCSS主题切换

因为SCSS是预编译语言,编译阶段无法读取浏览器端的Session Storage数据,所以必须结合JavaScript来实现动态主题切换,以下是两种可行方案:

方案一:使用CSS变量(推荐)

这种方式更灵活,无需重复编写样式,通过JS修改CSS变量值即可切换主题。

  1. 定义主题变量文件
    创建两个主题变量文件(例如_theme-light.scss和_theme-dark.scss):
// _theme-light.scss
$bg-color: #ffffff;
$text-color: #333333;
// _theme-dark.scss
$bg-color: #1a1a1a;
$text-color: #f5f5f5;
  1. 在styles.scss中关联CSS变量
    引入主题文件,并将SCSS变量映射为全局CSS变量,通过根元素属性区分主题:
@import './theme-light';
@import './theme-dark';

// 默认主题(浅色)
:root {
  --bg-color: $bg-color;
  --text-color: $text-color;
}

// 深色主题
[data-theme="dark"] {
  --bg-color: $bg-color;
  --text-color: $text-color;
}

// 全局样式使用CSS变量
body {
  background-color: var(--bg-color);
  color: var(--text-color);
  transition: all 0.3s ease; // 可选:添加切换过渡动画
}

// 其他组件样式同理
.card {
  border-color: var(--text-color);
}
  1. 编写JS逻辑读取Session Storage并切换主题
    在项目入口JS文件(如main.js)中添加:
// 读取Session Storage中保存的主题,默认浅色
const currentTheme = sessionStorage.getItem('theme') || 'light';
// 给根元素设置主题属性
document.documentElement.setAttribute('data-theme', currentTheme);

// 若需主题切换功能,可添加如下函数
function switchTheme(theme) {
  document.documentElement.setAttribute('data-theme', theme);
  sessionStorage.setItem('theme', theme);
}

方案二:使用SCSS混合宏生成主题类

通过SCSS预编译不同主题的样式类,再用JS切换DOM类名实现主题切换。

  1. 定义主题变量与混合宏
// 定义各主题变量
$theme-light: (
  bg-color: #ffffff,
  text-color: #333333
);
$theme-dark: (
  bg-color: #1a1a1a,
  text-color: #f5f5f5
);

// 定义主题样式混合宏
@mixin apply-theme($theme-map) {
  background-color: map-get($theme-map, bg-color);
  color: map-get($theme-map, text-color);
}

// 生成不同主题的全局样式类
.theme-light {
  @include apply-theme($theme-light);
}

.theme-dark {
  @include apply-theme($theme-dark);
}

// 默认应用浅色主题
body {
  @include apply-theme($theme-light);
}
  1. JS控制类名切换
const savedTheme = sessionStorage.getItem('theme') || 'light';
// 给body添加对应主题类
document.body.classList.add(`theme-${savedTheme}`);

// 主题切换函数
function switchTheme(theme) {
  // 移除旧主题类
  document.body.classList.remove('theme-light', 'theme-dark');
  // 添加新主题类
  document.body.classList.add(`theme-${theme}`);
  sessionStorage.setItem('theme', theme);
}

核心说明

SCSS在编译阶段就已生成静态CSS,无法直接读取浏览器的Session Storage,必须通过JS在运行时修改DOM的属性或类名,触发预编译好的不同主题样式生效。

内容的提问来源于stack exchange,提问作者M S

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.26 08:15:19