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

React网站添加主题切换时SCSS报SassError: $map: null错误求助

解决SassError: $map: null is not a map问题(React主题切换SCSS实现)

错误原因

你的代码里有两个核心问题:

  1. 你在themify mixin的循环结束后,通过$theme-map: null !global;把全局的$theme-map重置为null。当你在@include themify()代码块外部调用themed()函数时,map-get拿到的是null,直接触发报错。
  2. themify里的循环合并逻辑完全冗余——你已经拿到了当前主题的$map,没必要再重复从$themes里取值合并。

修复后的完整代码

$themes: (
  light: (
    textColor: #000,
    bg: white,
    logo: darkblue,
    bgSoft: #f6f3f3,
    textColorSoft: #555,
    border: lightgray,
  ),
  dark: (
    textColor: whitesmoke,
    bg: #222,
    logo: white,
    bgSoft: #333,
    textColorSoft: lightgray,
    border: #444,
  ),
);

@mixin themify($themes) {
  @each $theme, $map in $themes {
    .theme-#{$theme} & {
      // 直接将当前主题的map赋值给全局变量,省去冗余循环
      $theme-map: $map !global;
      @content;
      // 仅在当前主题作用域内用完后重置,避免污染全局
      $theme-map: null !global;
    }
  }
}

@function themed($key) {
  // 增加安全判断,避免theme-map为null时报错
  @if $theme-map and map-has-key($theme-map, $key) {
    @return map-get($theme-map, $key);
  }
  // 可选:默认返回light主题的对应值,保证无主题时的基础样式
  @return map-get(map-get($themes, 'light'), $key);
}

正确使用方式

所有调用themed()的样式,必须包裹在@include themify($themes)块内:

.header {
  @include themify($themes) {
    background-color: themed('bg');
    color: themed('textColor');
    border-color: themed('border');
  }
}

如果需要在themify外部获取主题值,直接从$themes map中读取:

// 获取dark主题的背景色
$dark-bg: map-get(map-get($themes, 'dark'), 'bg');

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.12 21:10:33