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

Chakra UI高级主题配置:如何移除所有预设颜色?

问题:如何在Chakra UI中移除所有预设颜色仅保留自定义配置?

在使用Chakra UI构建设计系统时,尝试移除所有预设颜色,仅保留自定义配置,但日志显示颜色对象中仍存在全部预设颜色:

Chakra UI颜色日志截图

相关代码

theme/index.tsx

import { extendTheme } from '@chakra-ui/react'
import { withProse } from '@nikolovlazar/chakra-ui-prose'

import { colors } from './colors'
import { components } from './components'
import { config } from './config'
import { fonts } from './fonts'

const customTheme = extendTheme({
  fonts,
  colors,
  config,
  components,
})

export default extendTheme(customTheme, withProse())

theme/colors.tsx

import type { DeepPartial, Theme } from '@chakra-ui/react'

// import { designSystemColors } from '@/designSystem'

const extendedColors: DeepPartial<
  Record<string, Theme['colors']['blackAlpha']>
> = {
  brand: {
    100: '',
    200: '',
    300: '',
    400: '',
    500: '',
    600: '',
    700: '',
    800: '',
    900: '',
  },
}

const overrideChakraColors: DeepPartial<Theme['colors']> = {}

export const colors = {
  ...overrideChakraColors,
  transparent: 'transparent',
  black: '#000000',
  white: '#ffffff',
  // ...designSystemColors,
  ...extendedColors,
}

theme/config.tsx

import type { ThemeConfig } from '@chakra-ui/react'

export const config: ThemeConfig = {
  initialColorMode: 'system',
  useSystemColorMode: false,
  disableTransitionOnChange: false,
}

解决方案

Chakra UI的extendTheme默认是合并用户配置与默认主题,而非完全覆盖。要彻底移除预设颜色,需直接替换整个colors对象,同时注意保留组件依赖的基础色(如transparent、black、white),具体步骤如下:

1. 重新定义颜色类型与对象

放弃使用DeepPartial<Theme['colors']>(该类型会保留默认主题的颜色结构),直接定义仅包含自定义颜色的类型与对象:

// theme/colors.tsx
type CustomColors = {
  transparent: string
  black: string
  white: string
  brand: {
    100: string
    200: string
    300: string
    400: string
    500: string
    600: string
    700: string
    800: string
    900: string
  }
  // 按需添加其他自定义颜色
}

export const colors: CustomColors = {
  transparent: 'transparent',
  black: '#000000',
  white: '#ffffff',
  brand: {
    100: '', // 替换为你的实际色值
    200: '',
    300: '',
    400: '',
    500: '',
    600: '',
    700: '',
    800: '',
    900: '',
  },
  // ...添加其他自定义颜色
}

2. 确保主题合并时颜色被完全覆盖

如果使用了withProse这类第三方插件,需在合并插件后再次明确覆盖colors,避免插件注入预设颜色:

// theme/index.tsx
import { extendTheme } from '@chakra-ui/react'
import { withProse } from '@nikolovlazar/chakra-ui-prose'

import { colors } from './colors'
import { components } from './components'
import { config } from './config'
import { fonts } from './fonts'

const baseTheme = {
  fonts,
  colors,
  config,
  components,
}

// 合并插件后再次覆盖colors,确保预设颜色被清除
export default extendTheme(baseTheme, withProse(), { colors })

额外注意事项

  • 检查项目中所有组件,确保没有使用Chakra预设颜色(如gray、blue等),否则会出现颜色缺失问题;
  • 可通过打印theme.colors验证是否仅保留了自定义颜色。

内容的提问来源于stack exchange,提问作者GʀᴜᴍᴘʏCᴀᴛ

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.05 02:42:32