如何通过Ant Design Design Token获取默认与暗黑主题的文本颜色?
在Ant Design中同时获取默认与暗黑主题的文本色
可以实现,下面提供两种实用方案:
方案1:预定义主题颜色映射
直接将Ant Design默认和暗黑主题的目标文本色提前定义为常量,无需依赖主题切换逻辑,直接根据条件调用:
// 预存官方默认与暗黑主题的主文本色(可从Ant Design主题文档获取最新值) const themeTextColors = { light: '#161823', dark: '#e6e6e6' }; // 根据当前主题和条件返回对应颜色 const getTargetTextColor = (x, currentTheme) => { return x ? themeTextColors[currentTheme] : themeTextColors[currentTheme === 'light' ? 'dark' : 'light']; };
方案2:动态生成双主题Token
借助@ant-design/cssinjs的主题生成能力,动态获取两套主题的完整Token集合,避免硬编码颜色值:
import { generateTheme } from '@ant-design/cssinjs'; import { defaultAlgorithm, darkAlgorithm } from '@ant-design/colors'; // 生成默认与暗黑主题的完整Token const lightTokens = generateTheme({ algorithm: defaultAlgorithm }); const darkTokens = generateTheme({ algorithm: darkAlgorithm }); // 按需提取并返回目标颜色 const getTargetTextColor = (x, currentTheme) => { const currentColor = currentTheme === 'light' ? lightTokens.colorText : darkTokens.colorText; const oppositeColor = currentTheme === 'light' ? darkTokens.colorText : lightTokens.colorText; return x ? currentColor : oppositeColor; };
关键注意点
- 需确保能正确获取当前主题标识(比如通过项目的状态管理工具或ThemeContext存储的
currentTheme值) - 若使用自定义主题,需将自定义配置传入
generateTheme,保证生成的Token与项目主题匹配
内容的提问来源于stack exchange,提问作者Heavenly Journey
相关产品推荐
相关产品推荐

