一,theme 配置文件(Ant Design 主题配置)
文件路径eg:styles/theme
import type { ThemeConfig } from 'antd';
const theme: ThemeConfig = {
token: {
colorPrimary: '#4a3c8c',
colorSuccess: '#2ecc71',
colorWarning: '#f39c12',
colorError: '#e74c3c',
colorInfo: '#3498db',
colorTextBase: '#333333',
borderRadius: 8,
},
components: {
Button: {
colorPrimary: '#4a3c8c',
colorPrimaryHover: '#5d4eb3',
},
},
};
export default theme;
该配置中包含了基础的主题令牌(如 colorPrimary: '#4a3c8c'、borderRadius: 8 等)和 Button 组件的定制样式。
二, 明暗模式主题扩展
基于导入的基础 theme,代码进一步扩展出了两种主题模式:
暗色模式(antdDarkTheme):
const antdDarkTheme = {
...theme, // 继承基础主题配置
token: {
...theme.token, // 继承基础令牌
// 新增/覆盖暗色模式专属令牌(文本色、背景色等)
colorText: 'white',
colorBgBase: '#374151',
// ...其他暗色模式样式
},
components: {
...theme.components, // 继承基础组件样式
// 新增/覆盖暗色模式下的组件样式(Form、Pagination等)
Form: { labelColor: 'white' },
// ...其他组件
},
algorithm: antdTheme.darkAlgorithm, // 应用antd官方暗色算法
};
亮色模式(antdLightTheme):
const antdLightTheme = {
...theme, // 直接复用基础主题配置
algorithm: antdTheme.defaultAlgorithm, // 应用antd官方默认亮色算法
};
三, 根据状态动态切换主题
通过 Redux 中的 mode 状态(dark 或默认亮色),动态选择应用哪种主题:
<ConfigProvider theme={mode === 'dark' ? antdDarkTheme : antdLightTheme}>
{/* 应用内容 */}
</ConfigProvider>
ConfigProvider 是 Ant Design 提供的全局配置组件,通过 theme 属性将你的主题配置应用到整个应用的所有 Ant Design 组件上。
四,配合暗色模式的全局样式处理
useEffect(() => {
if (mode === 'dark') {
document.documentElement.classList.add('dark');
} else {
document.documentElement.classList.remove('dark');
}
}, [mode]);
这段代码会在 mode 变化时,给 <html> 标签添加 / 移除 dark 类名,方便你在全局 CSS 中编写基于暗色模式的自定义样式(例如非 Ant Design 组件的样式)。
63

被折叠的 条评论
为什么被折叠?



