Ant Design Pro
是一個很是優秀的開箱即用的中臺前端/設計解決方案,私覺得有些地方過分封裝,固然這是見仁見智的見解。項目中遇到須要切換主題的需求,研究了一下,最後獲得了比較完美的結果。css
主題切換分爲兩個部分,一個是 Ant Design
組件的主題切換,另外一個是自定義組件的主題切換。下面分爲兩部分一個個解決。前端
Ant Design
組件在 V2 版本中,主題切換的功能是有Bug的,官方也不推薦使用,可是在 V4 版本中解決了此問題,通過本人測試,V4 版本的解決方案同時適應於 V2 版本。react
首先,安裝 umi-plugin-antd-theme
這個插件:git
npm i umi-plugin-antd-theme
複製代碼
這個插件的原理就是根據你的配置項,將 Ant Design
全部組件中的變量替換成你自定義的,生成多個主題.css
文件,放置在theme
文件夾下。github
將下面的代碼複製到config/config.*.js
文件中去,最後以下:npm
const plugins = [ [ 'umi-plugin-react', ... ], [ 'umi-plugin-antd-theme', { theme: [ { fileName: 'theme1.css', key:'theme1', modifyVars: { '@primary-color': '#13C2C2', '@menu-dark-color': '#324444', '@menu-dark-bg': '#5A5A5A', }, }, { fileName: 'theme2.css', key:'theme2', modifyVars: { '@primary-color': '#4992BF', '@menu-dark-color': '#9B9B9B', '@menu-dark-bg': '#3A3A3A', }, }, ], // 是否壓縮css min: true, // css module isModule: true, // 忽略 antd 的依賴 ignoreAntd: false, // 忽略 pro-layout ignoreProLayout: false, // 不使用緩存 cache: true, }, ], ]; 複製代碼
config/themePluginConfig.ts
添加相似代碼:export default { theme: [ ... { fileName: 'theme1.css', key:'theme1', modifyVars: { '@primary-color': '#13C2C2', '@menu-dark-color': '#324444', '@menu-dark-bg': '#5A5A5A', }, }, { fileName: 'theme2.css', key:'theme2', modifyVars: { '@primary-color': '#4992BF', '@menu-dark-color': '#9B9B9B', '@menu-dark-bg': '#3A3A3A', }, }, ], }; 複製代碼
在global.less
文件中,添加以下代碼:緩存
.body-wrap-theme1 { // theme1下的全局變量在此定義 --font-color: #000000; --bg-color: #011313; } .body-wrap-theme2 { // theme2下的全局變量在此定義 --font-color: #ffffff; --bg-color: #ffffff; } 複製代碼
自定義組件的index.less
中用法以下:bash
.flatButton{
color: var(--font-color);
backgroud: var(--bg-color);
}
複製代碼
在主題切換的方法中添加以下代碼,能夠根據本身須要進行修改,好比添加從本地獲取上次主題配置項等:markdown
theme1 = true; onClick = () => { let styleLink = document.getElementById("theme-style"); let body = document.getElementsByTagName('body')[0]; if (styleLink) { // 假如存在id爲theme-style 的link標籤,直接修改其href if (this.theme1) { styleLink.href = '/theme/theme1.css'; // 切換 ant design 組件主題 body.className = "body-wrap-theme1"; // 切換自定義組件的主題 } else { styleLink.href = '/theme/theme2.css'; body.className = "body-wrap-theme2"; } this.theme1 = !this.theme1; } else { // 不存在的話,則新建一個 styleLink = document.createElement('link'); styleLink.type = 'text/css'; styleLink.rel = 'stylesheet'; styleLink.id = 'theme-style'; if (this.theme1) { styleLink.href = '/theme/theme1.css'; body.className = "body-wrap-theme1"; } else { styleLink.href = '/theme/theme2.css'; body.className = "body-wrap-theme2"; } this.theme1 = !this.theme1; document.body.append(styleLink); } } 複製代碼
這個實現的思路容易理解,一個是替換CSS文件,一個是css
自帶的 var
替換變量。PS:感謝同事梁老師的幫助antd
JerryMissTom是個人 GitHub
地址,歡迎Follow