前言
我们经常会使用 antd、element-plus的库,然后有一些甚至不会更新他们的主题色,就统一设置css,很是麻烦,实际上有主题色这种东西可以一键设置,更改也很方便
antd主题
//配置主题色
<ConfigProvider
theme={{
token: {
colorPrimary: '#00b96b',
},
}}
>
...
</ConfigProvider>
//配置某一些组件主题
<ConfigProvider
theme={{
components: {
Button: {
colorPrimary: '#00b96b',
algorithm: true, // 启用算法
},
Input: {
colorPrimary: '#eb2f96',
algorithm: true, // 启用算法
}
},
}}
>
...
</ConfigProvider>
//设置算法
- 默认算法 `theme.defaultAlgorithm`
- 暗色算法 `theme.darkAlgorithm`
- 紧凑算法 `theme.compactAlgorithm`
<ConfigProvider
theme={{
// 1. 单独使用暗色算法
algorithm: theme.darkAlgorithm,
// 2. 组合使用暗色算法与紧凑算法
// algorithm: [theme.darkAlgorithm, theme.compactAlgorithm],
}}
>
...
</ConfigProvider>
//也可以通过 useToken 使用 antd 的通用颜色属性
import { theme } from 'antd';
const { useToken } = theme;
const App: React.FC = () => {
const { token } = useToken();
token.colorPrimary //可以使用antdd的
}
element-plus主题
使用 element-plus 时,更新主题一般是直接更新 element-plus 的 css 变量,自己如果需要和 element-plus 使用同一个主题,可以使用 tailwind 或者其他全局 css 变量等,共同使用同一个颜色,
//直接更新默认 element-plus css变量
:root {
--el-color-primary: green;
}
//如果想全局改一个参数就完事了,可以设置一个变量,然后统一应用即可,需要注意自己项目主题色也需要统一
const primaryColor = blue;
document.documentElement.style.setProperty('--el-color-primary', primaryColor);
//使用tailwind定义通用css class,可以和 element-plus使用同一个主题色
.tailwind.config.js
extend: {
colors: {
primary: {
DEFAULT: 'var(--el-color-primary)',
}
}
}
最后
要是想动态修改主题色,可以直接动态修改变量、css变量等方式修改主题,就可以了,甚至可以保存到 localStorage