0
点赞
收藏
分享

微信扫一扫

Create Dynamic theme with antd and reactjs


说在前面

由于业务需要,在用蚂蚁金服antd组件库时需要设置两种主题色动态切换。在这里踩了一些坑,觉得有必要写一篇水文记录一下。

步骤

  • 安装webpack插件以进行动态主题化
cnpm install antd-theme-webpack-plugin
  • 在您的​​webpack.config.js​​文件中导入此插件,使用有效的路径参数初始化并在webpack配置对象中添加插件数组。
const AntDesignThemePlugin = require('antd-theme-webpack-plugin'); 

const options = {
antDir:path.join(__ dirname,'。/ node_modules
/antd'),stylesDir:path.join(__ dirname,'。/ src / styles'),
varFile:path.join(__ dirname,'。/ src /styles/variables.less'),
mainLessFile:path.join(__
dirname,'。/ src / styles / index.less'),
themeVariables:['@ primary-color'],
indexFileName:'index.html'
}

const themePlugin = new AntDesignThemePlugin(options);
//在插件部分,添加此插件实例
插件: [themePlugin,其他一些插件]

  • ​antDir​​​如果​​webpack.config.js​​​文件和​​node_modules​​目录位于项目目录结构的根级别,则路径将相同。
  • 默认​​stylesDir​​​是​​/src/styles​​包含较少文件中的自定义样式的目录
  • ​mainLessFile​​包含所有自定义样式导入的文件较少

@import 'variables';
@import './components/app'
  • ​varFile​​是包含变量的文件,其中包含您要覆盖的Ant Design中的变量。确保已在文件中导入Ant Design主题varFile文件。
@import "../../node_modules/antd/lib/style/themes/default";
@primary-color: #1C66ED;

  • ​themeVariables​​是要在浏览器中更改的颜色特定变量名称数组。默认是​​[ '@primary-color' ]​
  • ​indexFileName​​这只是文件名而不是路径。如果您的构建过程将生成一个html文件,那么这就是html文件的名称。主要是​​index.html​​。但是如果webpack没有生成那个主要的html文件,那么你需要在你的html文件中手动插入几行,这是使用在需要切换主题的时候动态添加需要的文件

const lessStyleNode = document.createElement('link');
const lessConfigNode = document.createElement('script');
const lessScriptNode = document.createElement('script');
lessStyleNode.setAttribute('rel', 'stylesheet/less');
lessStyleNode.setAttribute('href', '/color.less');
lessConfigNode.innerHTML = `
window.less = {
async: true,
env: 'production',
javascriptEnabled: true
};
`;
lessScriptNode.src = 'https://gw.alipayobjects.com/os/lib/less.js/3.8.1/less.min.js';
lessScriptNode.async = true;
lessScriptNode.onload = () => {
//修改主题的方法
lessScriptNode.onload = null;
};
document.body.appendChild(lessStyleNode);
document.body.appendChild(lessConfigNode);
document.body.appendChild(lessScriptNode);

  • 这里能够动态修改主题的原来是,在浏览器上直接运行​​less​​文件(通过less.js),然后异步的去设置一份​​color.less​​去覆盖掉antd的默认样式。从而达到动态修改主题的需求。
  • 现在一切都准备好了。您需要编写代码,以便通过调用​​less.modifyVar()​​函数来更新更少的变量。您可以使用任何有效的颜色值进行调用,主题将更新。您可以像这样在React组件中添加方法

changeColor =(colorCode)=> { 
window.less.modifyVars({
'@ primary-color`:colorCode
});
}

或者你甚至可以使它成为通用的

changeColor =(variableName,colorCode)=> { 
window.less.modifyVars({
[variableName]:colorCode
});
}

您只能更新您提供的那些颜色变量​​themeVariables​​。

文章参考

​​​https://github.com/ant-design/ant-design-pro/blob/master/src/models/setting.js#L34​​​

​​​https://medium.com/@mzohaib.qc/ant-design-dynamic-runtime-theme-1f9a1a030ba0​​​


举报

相关推荐

0 条评论