全局主题样式定制

一,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 组件的样式)。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值