使用 sass 和 css 模块主题化 React 应用程序

tom*_*ole 4 sass reactjs css-modules

我想在我的反应应用程序中实现主题。因此我使用了这个教程(sass-mixins)。

但这不能与 css-modules 结合使用,因为主题类位于我想要主题化的 css-module 之外。

有没有人有解决此问题的方法或使用 sass 主题化反应应用程序的另一种方法?

应用程序.js

const theme = require('../../Theming.sass)

<div class={theme['theme-dark'}>
  <SearchBar/>
  ...
</div>
Run Code Online (Sandbox Code Playgroud)

搜索栏.js

const styles = require('./SearchBar.scss)
const theme = require('../../Theming.sass)

<div class={styles.searchBar}>
  ...
</div>
Run Code Online (Sandbox Code Playgroud)

搜索栏.scss

.searchBar {
  @include themify($themes) {
    color: themed('primary');
    background: themed('secondary');
  }

  height: 3em;
  overflow: hidden;
Run Code Online (Sandbox Code Playgroud)

SearchBar.css(已编译)

.searchBar {
  height: 3em;
  overflow: hidden;
}

.theme-light .searchBar {
  color: #fff;
  background: #bfbfbf;
}

.theme-dark .searchBar {
  color: #000;
  background: #1a1a1a;
}
Run Code Online (Sandbox Code Playgroud)

主题化.sass

.theme-dark { background: #000; }

.theme-light { background: #fff; }

$themes: (
  light: (
    primary: #fff,
    secondary: #bfbfbf,
  ),
  dark: (
    primary: #000,
    secondary: #1a1a1a,
  ),
);

@function themed($key) {
  @return map-get($theme-map, $key);
}

@mixin themify($themes: $themes) {
  @each $theme, $map in $themes {

    .theme-#{$theme} & { /* HOW TO USE CSS-MODULES HERE ?*/
      $theme-map: () !global;
      @each $key, $submap in $map {
        $value: map-get(map-get($themes, $theme), '#{$key}');
        $theme-map: map-merge($theme-map, ($key: $value)) !global;
      }

      @content;
      $theme-map: null !global;
    }

  }
}
Run Code Online (Sandbox Code Playgroud)

小智 7

我遇到了类似的问题,我在 React 应用程序中使用 SASS 和 CSS 模块,最终我使用主题类作为全局类,而不是使用 CSS 模块,因为每次我使用 mixin 时,它都会将模块前缀添加到样式中。

:global在 mixin 中添加了主题类:

@mixin themify($themes: $themes) {
  @each $theme, $map in $themes {

    :global(.theme-#{$theme}) & { 
      $theme-map: () !global;
      @each $key, $submap in $map {
        $value: map-get(map-get($themes, $theme), '#{$key}');
        $theme-map: map-merge($theme-map, ($key: $value)) !global;
      }

      @content;
      $theme-map: null !global;
    }

  }
}
Run Code Online (Sandbox Code Playgroud)

我直接在 App.js 的 JSX 中指定了该类:

<div class="theme-dark">
  <SearchBar/>
  ...
</div>
Run Code Online (Sandbox Code Playgroud)

我希望这可以帮助别人。