You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在Theme-UI主题配置中定义深色模式下的按钮颜色?

Theme-UI中配置深色模式按钮颜色的正确方式

你当前的配置逻辑有误,Theme-UI里深色模式的样式不是通过嵌套在按钮变体的variants中来实现的——你这样写的dark只是按钮的一个自定义变体,需要手动指定<Button variant="primary.dark">才会生效,而非跟随系统或应用的深色模式自动切换。

下面是两种正确的配置方式:

方法一:通过主题颜色体系统一配置深色模式

在主题的colors.modes中定义深色模式下的全局颜色,然后按钮变体直接引用这些颜色,Theme-UI会自动根据当前的colorMode切换样式:

const theme = {
  colors: {
    // 浅色模式默认颜色
    text: '#000',
    background: '#fff',
    primary: '#000',
    // 深色模式下的颜色配置
    modes: {
      dark: {
        text: '#fff',
        background: '#000',
        primary: '#fff',
      },
    },
  },
  buttons: {
    primary: {
      color: 'background', // 浅色模式取白色,深色模式取黑色
      bg: 'primary', // 浅色模式取黑色,深色模式取白色
    },
  },
};

这种方式的好处是整个主题的颜色体系统一,所有引用这些颜色的组件都会自动适配深色模式。

方法二:给按钮单独设置深色模式样式

如果只需要给按钮单独配置深色模式样式,可以使用媒体查询或者Theme-UI的colorMode变量:

媒体查询方式(跟随系统深色模式)

const theme = {
  buttons: {
    primary: {
      color: 'white',
      bg: 'black',
      // 系统切换到深色模式时生效
      '@media (prefers-color-scheme: dark)': {
        color: 'black',
        bg: 'white',
      },
    },
  },
};

基于Theme-UI colorMode的条件样式

const theme = {
  buttons: {
    primary: {
      color: props => props.theme.colorMode === 'dark' ? 'black' : 'white',
      bg: props => props.theme.colorMode === 'dark' ? 'white' : 'black',
    },
  },
};

注意:无论用哪种方式,都需要确保你的应用已经通过ColorModeProvider包裹,这样Theme-UI才能识别和切换colorMode。

内容的提问来源于stack exchange,提问作者David

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.26 21:32:25