react-scss 两种不同需求换肤方案

517 阅读1分钟

一、需求一:有固定的换肤,如:light,dark

  1. 先定义好两套主题,_theme.scss

    // 默认主题 default-theme : ( bg-color: #2bf308, text-color: #ef0707 ); //红色主题 red-theme:( bg-color: red, text-color: #070707 ); //定义映射集合 themes:(defaulttheme:themes: ( default-theme: default-theme, red-theme: $red-theme );

  2. 编写minxins

    // 定义背景颜色使用 @mixin theme-background(){ @each themename,themename , theme in themes { [data-theme = '#{themename}'] & { background-color: map-get(map:map: theme, key: bg-color ) } } } // 定义文字颜色使用 @mixin theme-text-color(){ @each themename , themeintheme in themes { [data-theme = '#{themename}'] & { color: map-get(map: theme,theme, key: text-color ) } } }

3、使用方法,默认使用default-theme主题,在store中存储default-theme,当更换主题,theme也随之变化,

index.scss文件内容

.theme-test-wrap { 
 width: 70vw; 
 height: 25vw; 
 margin: 20vw auto; 
   &-content {   
     font-size: 50px; 
     @include theme-background(); 
     @include theme-text-color();  
   }
}

效果如下

二、需求二、可随机更改颜色值的主题配置

1、定义好默认主题的颜色配置,如theme.css

.theme-test-wrap2-content2 {   
   color: #2bf308;   
   background: #ef0707;
}

2、页面如下

3、自定义hook useTheme实现

4、utils实现

总结:第一种就是css的选择器添加前缀实现的方案

            第二种就是通过css覆盖的方案

第一次写,感觉写的很简单,不会描述,请大家见谅