在 Chakra 中构建设计系统,我试图弄清楚如何将所有预设颜色删除为我指定的颜色,但由于某种原因,当我记录主题时,我可以看到颜色对象中仍然存在所有内容:
主题/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())
主题/颜色.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,
}
主题/config.tsx:
import type { ThemeConfig } from '@chakra-ui/react'
export const config: ThemeConfig = {
initialColorMode: 'system',
useSystemColorMode: false,
disableTransitionOnChange: false,
}
在 Chakra UI 主题中,如何删除主题的所有预设颜色?
将自定义主题与默认主题合并是
extendTheme
1 的预期行为。
要覆盖主题以删除颜色,请创建一个主题对象,而不是使用
extendTheme
,并将其传递给 ChakraProvider
主题道具。如果不与 Chakra UI 主题合并,Chakra UI 样式将会丢失。
为了防止这种情况,可以手动合并 Chakra 主题和自定义主题,同时忽略要删除的 Chakra 主题的属性。
对于颜色,我建议保留
black
、blackAlpha
、currentColor
、gray
、transparent
、white
和 whiteAlpha
,因为 Chakra UI 基本样式经常使用这些颜色。如果删除这些标记,则需要自定义许多基本组件样式以弥补它们的损失。
当修改其他主题元素并希望保留 Chakra UI 基本样式时,请确保将 Chakra UI 基本样式复制到修改后的元素中。
下面的示例使用扩展运算符,但使用您喜欢的任何对象合并方法。
import {theme, type Colors} from "@chakra-ui/react";
const customColors: Colors = {
brand: {
50: "#f5faff",
100: "#eaf2ff",
200: "#c8dfff",
300: "#a6ccff",
400: "#63a3ff",
500: "#208aff",
600: "#1d74e6",
700: "#174fb4",
800: "#123a89",
900: "#0d275e",
}
}
export const mergedTheme: Record<keyof typeof theme, unknown> = {
...theme,
colors: {
// Chakra UI base colors used heavily in theme styles
black: "#000000",
blackAlpha: {...theme.colors.blackAlpha},
currentColor: "currentColor",
gray: {...theme.colors.gray},
transparent: "transparent",
white: "#ffffff",
whiteAlpha: {...theme.colors.whiteAlpha},
// Add custom colors
...customColors,
},
borders: {
// Keep Chakra UI base borders
...theme.borders,
// Add custom borders
"3px": "3px solid",
}
}
上面删除了除指定颜色之外的 Chakra UI 颜色。希望这有帮助!
参考
1 chakra-ui GitHub:
extendTheme
的源代码