自定义
了解如何自定义 Chakra UI 主题
概述
¥Overview
Chakra UI 使用配置系统来定义默认样式系统。
¥Chakra UI uses a system of configs to define the default styling system.
-
defaultBaseConfig
:包含条件和样式属性(不包括令牌和配方)。 -
defaultConfig
:defaultBaseConfig
的所有内容以及内置令牌和配方。
从 Chakra UI 导出的 defaultSystem
默认使用 defaultConfig
。
¥The defaultSystem
exported from Chakra UI uses the defaultConfig
by default.
自定义主题时,务必确定是将配置与 defaultConfig
合并,还是从 defaultBaseConfig
开始。
¥When customizing the theme, it's important to decide if you want to merge your
config with defaultConfig
or start from scratch with defaultBaseConfig
.
自定义
¥Customization
这些是自定义 Chakra UI 主题所需的关键函数。
¥These are the key functions needed to customize the Chakra UI theme.
-
defineConfig
:用于定义系统配置 -
createSystem
:用于从配置创建样式引擎
theme.ts
import { createSystem, defaultConfig, defineConfig } from "@chakra-ui/react"
const config = defineConfig({
theme: {
tokens: {
colors: {
brand: {
"500": { value: "tomato" },
},
},
},
},
})
export const system = createSystem(defaultConfig, config)
接下来,更新 ChakraProvider
以使用自定义系统。
¥Next, update the ChakraProvider
to use the custom system.
provider.tsx
import { ChakraProvider } from "@chakra-ui/react"
import { ThemeProvider } from "next-themes"
import { system } from "./theme"
export function Provider(props: { children: React.ReactNode }) {
return (
<ChakraProvider value={system}>
<ThemeProvider attribute="class">{props.children}</ThemeProvider>
</ChakraProvider>
)
}
完全自定义
¥Complete Customization
在大多数情况下,我们建议从默认配置开始,并仅指定你想要自定义的内容。
¥In most cases, we recommend starting with the default configuration and only specify the things you want to customize.
但是,如果你希望从头开始,请使用 CLI 搭建默认令牌和配方。
¥However, if you prefer to start from scratch, scaffold the default tokens and recipes using the CLI.
npx @chakra-ui/cli eject --outdir ./theme
这将生成一个包含 Chakra 中所有令牌和配方的文件。
¥This will generate a file that includes all the tokens and recipes in Chakra.
TypeScript
自定义默认配置后,你可能需要更新类型。
¥After customizing the default config, you may need to update the types.
npx @chakra-ui/cli typegen ./theme.ts