使用高级 Chakra UI 组件,更快地构建 💎

了解更多

创建自定义颜色

2024年11月15日

要在 Chakra UI 中创建自定义颜色,你需要定义两件事

要了解更多关于 tokens 和 semantic tokens 的信息,请参考主题化指南.

components/theme.ts

const config = defineConfig({
  theme: {
    tokens: {
      colors: {
        brand: {
          50: { value: "#e6f2ff" },
          100: { value: "#e6f2ff" },
          200: { value: "#bfdeff" },
          300: { value: "#99caff" },
          // ...
          950: { value: "#001a33" },
        },
      },
    },
    semanticTokens: {
      colors: {
        brand: {
          solid: { value: "{colors.brand.500}" },
          contrast: { value: "{colors.brand.100}" },
          fg: { value: "{colors.brand.700}" },
          muted: { value: "{colors.brand.100}" },
          subtle: { value: "{colors.brand.200}" },
          emphasized: { value: "{colors.brand.300}" },
          focusRing: { value: "{colors.brand.500}" },
        },
      },
    },
  },
})

export const system = createSystem(defaultConfig, config)

接下来,你将新的 system 添加到你的 components/ui/provider.tsx 文件中

"use client"

import { system } from "@/components/theme"
import {
  ColorModeProvider,
  type ColorModeProviderProps,
} from "@/components/ui/color-mode"
import { ChakraProvider } from "@chakra-ui/react"

export function Provider(props: ColorModeProviderProps) {
  return (
    <ChakraProvider value={system}>
      <ColorModeProvider {...props} />
    </ChakraProvider>
  )
}

接下来,运行 CLI typegen 命令来生成类型。

npx chakra typegen ./theme.ts

使用颜色

完成设置后,你可以在组件中以及 colorPalette 工具中使用这些颜色。

<Button colorPalette="brand">Click me</Button>

你也可以直接使用 semantic token。

<Box color="brand.contrast" bg="brand.solid">
  Hello world
</Box>

或者,你可以使用原始的 token 值。

<Box color="brand.500">Hello world</Box>