实用工具
实用工具 API 是一种创建自定义 CSS 属性、将现有属性映射到一组值或令牌的方式。
以下是定义或自定义实用工具所需的属性
shorthand
: 属性的缩写或别名版本values
: 属性可能的值。可以是令牌类别、枚举值、字符串、数字或布尔值。transform
: 一个将值转换为有效 CSS 对象的函数
创建自定义实用工具
假设您想创建一个新属性 br
用于为元素应用边框半径。
components/ui/provider.tsx
import { createSystem, defaultConfig, defineConfig } from "@chakra-ui/react"
const customConfig = defineConfig({
utilities: {
extend: {
br: {
values: "radii",
transform(value) {
return { borderRadius: value }
},
},
},
},
})
const system = createSystem(defaultConfig, customConfig)
现在,您可以在组件中使用 br
属性。
app.tsx
import { Box } from "@chakra-ui/react"
function App() {
return <Box br="sm" />
}
使用枚举值
假设我们想创建一个新属性 borderX
用于为元素应用一组有限的内联边框并自动应用边框颜色。
components/ui/provider.tsx
import { createSystem, defaultConfig, defineConfig } from "@chakra-ui/react"
const customConfig = defineConfig({
utilities: {
extend: {
borderX: {
values: ["1px", "2px", "4px"],
shorthand: "bx",
transform(value, { token }) {
return {
borderInlineWidth: value,
borderColor: token("colors.red.200"),
}
},
},
},
},
})
const system = createSystem(defaultConfig, customConfig)
现在,您可以在组件中使用 borderX
或 bx
属性。
app.tsx
import { Box } from "@chakra-ui/react"
function App() {
return <Box borderX="sm" />
}
使用映射值
components/ui/provider.tsx
import { createSystem, defaultConfig, defineConfig } from "@chakra-ui/react"
const customConfig = defineConfig({
utilities: {
extend: {
borderX: {
values: { small: "2px", medium: "5px" },
shorthand: "bx",
transform(value, { token }) {
return {
borderTopWidth: value,
borderTopColor: token("colors.gray.400"),
}
},
},
},
},
})
const system = createSystem(defaultConfig, customConfig)
现在,您可以在组件中使用 borderX
或 bx
属性。
app.tsx
import { Box } from "@chakra-ui/react"
function App() {
return <Box borderX="sm" />
}