实用程序
实用程序 API 是一种创建自定义 CSS 属性、将现有属性映射到一组值或标记的方法。
以下是定义或自定义实用程序所需的属性:
¥Here are the properties you need to define or customize a utility:
-
shorthand
:该属性的简写或别名版本 -
values
:该属性可能具有的值。可以是 token 类别,也可以是枚举值、字符串、数字或布尔值。 -
transform
:将值转换为有效 CSS 对象的函数
创建自定义实用程序
¥Creating a custom utility
假设你要创建一个新的属性 br
,为元素应用边框半径。
¥Let's say you want to create new property br
that applies a border radius to
an element.
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
属性。
¥Now, you can use the br
property in components.
app.tsx
import { Box } from "@chakra-ui/react"
function App() {
return <Box br="sm" />
}
使用枚举值
¥Using enum values
假设我们要创建一个新的属性 borderX
,为元素应用一组有限的内联边框并自动应用边框颜色。
¥Let's say we want to create a new property borderX
that applies a limited set
of inline border to an element and automatically applies the border color.
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
属性。
¥Now, you can use the borderX
or bx
property in components.
app.tsx
import { Box } from "@chakra-ui/react"
function App() {
return <Box borderX="sm" />
}
使用映射值
¥Using mapped values
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
属性。
¥Now, you can use the borderX
or bx
property in components.
app.tsx
import { Box } from "@chakra-ui/react"
function App() {
return <Box borderX="sm" />
}