React项目在线切换antd主题

1、安装插件

npm install antd-theme-generator

2、src文件夹下添加styles/index.less+styles/variables.less

根目录新建color.js

const path = require('path');
const { generateTheme } = require('antd-theme-generator');
const options = {
  stylesDir: path.join(__dirname, './src/styles'),
  antDir: path.join(__dirname, './node_modules/antd'),
  varFile: path.join(__dirname, './src/styles/variables.less'),
  mainLessFile: path.join(__dirname, './src/styles/index.less'),
  themeVariables: [
    //需要动态切换的主题变量
    '@primary-color',
    '@secondary-color',
    '@text-color',
    '@text-color-secondary',
    '@heading-color',
    '@layout-body-background'
  ],
  indexFileName: 'index.html',
  outputFilePath: path.join(__dirname, './public/color.less') //页面引入的主题变量文件
};
generateTheme(options)
  .then(less => {
    console.log('Theme generated successfully');
  })
  .catch(error => {
    console.log('Error', error);
  });

3、src文件夹下添加styles/index.less+styles/variables.less

@import '~antd/lib/style/themes/default.less';

4、index.html文件中加入全局less配置

index.html 中加入全局 less 变量配置,从而使 less 的 modifyVars 方法可以全局使用,切换主题时覆盖 default.less 中的变量:

<body>
    <link
      rel="stylesheet/less"
      type="text/css"
      href="%PUBLIC_URL%/color.less"
      rel="external nofollow"
    />
    <script>
      window.less = {
        async: false,
        env: 'production'
      };
    </script>
    <script
      type="text/javascript"
      src="https://cdnjs.cloudflare.com/ajax/libs/less.js/2.7.2/less.min.js"
    ></script>
    <div id="root" style="height: 100%;"></div>
  </body>

5、package.json文件修改命令

"scripts": {
  	"start": "node color && react-scripts start",
 	"build": "node color && react-scripts start",
	"test": " node color && react-scripts start"
},

6、动态修改颜色

getTheme = color => {
    window.less
      .modifyVars({
        '@primary-color': color,
      })
      .then(() => {
        consolr.log(color);
      })
      .catch(error => {
        console.log(error);
      });
  };
  • 2
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 4
    评论
评论 4
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值