语义化令牌
在您的应用中利用语义化令牌进行设计决策。
概述
语义化令牌是旨在特定上下文使用的令牌。一个语义化令牌包含以下属性:
value
:令牌的值或对现有令牌的引用。description
:关于令牌用途的描述(可选)。
定义语义化令牌
在大多数情况下,语义化令牌的值引用现有令牌。
要在语义化令牌中引用一个值,请使用令牌引用 {}
语法。
theme.ts
import { createSystem, defaultConfig, defineConfig } from "@chakra-ui/react"
const config = defineConfig({
theme: {
tokens: {
colors: {
red: { value: "#EE0F0F" },
},
},
semanticTokens: {
colors: {
danger: { value: "{colors.red}" },
},
},
},
})
export default createSystem(defaultConfig, config)
使用语义化令牌
定义语义化令牌后,我们建议使用 Chakra CLI 为您的令牌生成主题类型定义。
npx @chakra-ui/cli typegen ./src/theme.ts
这将在您的编辑器中为您的令牌提供自动补全功能。
<Box color="danger">Hello World</Box>
条件令牌
语义化令牌也可以根据明暗模式等条件进行更改。
例如,如果您希望颜色根据明暗模式自动变化。
theme.ts
import { createSystem, defaultConfig, defineConfig } from "@chakra-ui/react"
const config = defineConfig({
theme: {
semanticTokens: {
colors: {
danger: {
value: { base: "{colors.red}", _dark: "{colors.darkred}" },
},
success: {
value: { base: "{colors.green}", _dark: "{colors.darkgreen}" },
},
},
},
},
})
export default createSystem(defaultConfig, config)
信息
语义化令牌中使用的条件必须是 at-rule 或父选择器 条件。语义化令牌嵌套
语义化令牌可以嵌套以创建令牌的层次结构。当您想要将令牌分组时,这会很有用。
信息
使用 DEFAULT
键来定义嵌套令牌的默认值。theme.ts
import { createSystem, defaultConfig, defineConfig } from "@chakra-ui/react"
const config = defineConfig({
theme: {
semanticTokens: {
colors: {
bg: {
DEFAULT: { value: "{colors.gray.100}" },
primary: { value: "{colors.teal.100}" },
secondary: { value: "{colors.gray.100}" },
},
},
},
},
})
export default createSystem(defaultConfig, config)
这允许以下列方式使用 bg
令牌:
<Box bg="bg">
<Box bg="bg.primary">Hello World</Box>
<Box bg="bg.secondary">Hello World</Box>
</Box>