Field(表单字段)
将标签、控件和帮助文本组合为无障碍表单字段和输入组。
安装
npx shadcn@latest add field1. 将以下代码复制并粘贴到项目中。
"use client"
import { useMemo } from "react"
import { cva, type VariantProps } from "class-variance-authority"
import { cn } from "cn"
import { Label } from "./label"
import { Separator } from "./separator"
function FieldSet({ className, ...props }: React.ComponentProps<"fieldset">) {
return (
<fieldset
data-slot="field-set"
className={cn(
"flex flex-col gap-6 has-[>[data-slot=checkbox-group]]:gap-3 has-[>[data-slot=radio-group]]:gap-3",
className
)}
{...props}
/>
)
}
function FieldLegend({
className,
variant = "legend",
...props
}: React.ComponentProps<"legend"> & { variant?: "legend" | "label" }) {
return (
<legend
data-slot="field-legend"
data-variant={variant}
className={cn(
"mb-3 font-medium data-[variant=label]:text-sm data-[variant=legend]:text-base",
className
)}
{...props}
/>
)
}
function FieldGroup({ className, ...props }: React.ComponentProps<"div">) {
return (
<div
data-slot="field-group"
className={cn(
"group/field-group @container/field-group flex w-full flex-col gap-7 data-[slot=checkbox-group]:gap-3 *:data-[slot=field-group]:gap-4",
className
)}
{...props}
/>
)
}
const fieldVariants = cva(
"group/field flex w-full gap-3 data-[invalid=true]:text-destructive",
{
variants: {
orientation: {
vertical: "flex-col *:w-full [&>.sr-only]:w-auto",
horizontal:
"flex-row items-center has-[>[data-slot=field-content]]:items-start *:data-[slot=field-label]:flex-auto has-[>[data-slot=field-content]]:[&>[role=checkbox],[role=radio]]:mt-px",
responsive:
"flex-col *:w-full @md/field-group:flex-row @md/field-group:items-center @md/field-group:*:w-auto @md/field-group:has-[>[data-slot=field-content]]:items-start @md/field-group:*:data-[slot=field-label]:flex-auto [&>.sr-only]:w-auto @md/field-group:has-[>[data-slot=field-content]]:[&>[role=checkbox],[role=radio]]:mt-px",
},
},
defaultVariants: {
orientation: "vertical",
},
}
)
function Field({
className,
orientation = "vertical",
...props
}: React.ComponentProps<"div"> & VariantProps<typeof fieldVariants>) {
return (
<div
role="group"
data-slot="field"
data-orientation={orientation}
className={cn(fieldVariants({ orientation }), className)}
{...props}
/>
)
}
function FieldContent({ className, ...props }: React.ComponentProps<"div">) {
return (
<div
data-slot="field-content"
className={cn(
"group/field-content flex flex-1 flex-col gap-1 leading-snug",
className
)}
{...props}
/>
)
}
function FieldLabel({
className,
...props
}: React.ComponentProps<typeof Label>) {
return (
<Label
data-slot="field-label"
className={cn(
"group/field-label peer/field-label flex w-fit gap-2 leading-snug group-data-[disabled=true]/field:opacity-50 has-data-checked:border-primary/30 has-data-checked:bg-primary/5 has-[>[data-slot=field]]:rounded-xl has-[>[data-slot=field]]:border has-[>[data-slot=field]]:not-has-[:disabled,[data-disabled]]:hover:bg-input/40 has-[>[data-slot=field]]:has-[:focus-visible]:border-ring has-[>[data-slot=field]]:has-[:focus-visible]:ring-[3px] has-[>[data-slot=field]]:has-[:focus-visible]:ring-ring/50 *:data-[slot=field]:p-4 dark:has-data-checked:border-primary/20 dark:has-data-checked:bg-primary/10",
"has-[>[data-slot=field]]:w-full has-[>[data-slot=field]]:flex-col",
className
)}
{...props}
/>
)
}
function FieldTitle({ className, ...props }: React.ComponentProps<"div">) {
return (
<div
data-slot="field-label"
className={cn(
"flex w-fit items-center gap-2 text-sm font-medium group-data-[disabled=true]/field:opacity-50",
className
)}
{...props}
/>
)
}
function FieldDescription({ className, ...props }: React.ComponentProps<"p">) {
return (
<p
data-slot="field-description"
className={cn(
"text-start text-sm leading-normal font-normal text-muted-foreground group-has-data-horizontal/field:text-balance [[data-variant=legend]+&]:-mt-1.5",
"last:mt-0 nth-last-2:-mt-1",
"[&>a]:underline [&>a]:underline-offset-4 [&>a:hover]:text-primary",
className
)}
{...props}
/>
)
}
function FieldSeparator({
children,
className,
...props
}: React.ComponentProps<"div"> & {
children?: React.ReactNode
}) {
return (
<div
data-slot="field-separator"
data-content={!!children}
className={cn(
"relative -my-2 h-5 text-sm group-data-[variant=outline]/field-group:-mb-2",
className
)}
{...props}
>
<Separator className="absolute inset-0 top-1/2" />
{children && (
<span
className="relative mx-auto block w-fit bg-background px-2 text-muted-foreground"
data-slot="field-separator-content"
>
{children}
</span>
)}
</div>
)
}
function FieldError({
className,
children,
errors,
...props
}: React.ComponentProps<"div"> & {
errors?: Array<{ message?: string } | undefined>
}) {
const content = useMemo(() => {
if (children) {
return children
}
if (!errors?.length) {
return null
}
const uniqueErrors = [
...new Map(errors.map((error) => [error?.message, error])).values(),
]
if (uniqueErrors?.length == 1) {
return uniqueErrors[0]?.message
}
return (
<ul className="ms-4 flex list-disc flex-col gap-1">
{uniqueErrors.map(
(error, index) =>
error?.message && <li key={index}>{error.message}</li>
)}
</ul>
)
}, [children, errors])
if (!content) {
return null
}
return (
<div
role="alert"
data-slot="field-error"
className={cn("text-sm font-normal text-destructive", className)}
{...props}
>
{content}
</div>
)
}
export {
Field,
FieldLabel,
FieldDescription,
FieldError,
FieldGroup,
FieldLegend,
FieldSeparator,
FieldSet,
FieldContent,
FieldTitle,
}2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
2. 根据项目配置调整导入路径。
用法
import {
Field,
FieldContent,
FieldDescription,
FieldError,
FieldGroup,
FieldLabel,
FieldLegend,
FieldSeparator,
FieldSet,
FieldTitle,
} from "@/components/ui/field"2
3
4
5
6
7
8
9
10
11
12
<FieldSet>
<FieldLegend>Profile</FieldLegend>
<FieldDescription>This appears on invoices and emails.</FieldDescription>
<FieldGroup>
<Field>
<FieldLabel htmlFor="name">Full name</FieldLabel>
<Input id="name" autoComplete="off" placeholder="Evil Rabbit" />
<FieldDescription>This appears on invoices and emails.</FieldDescription>
</Field>
<Field>
<FieldLabel htmlFor="username">Username</FieldLabel>
<Input id="username" autoComplete="off" aria-invalid />
<FieldError>Choose another username.</FieldError>
</Field>
<Field orientation="horizontal">
<Switch id="newsletter" />
<FieldLabel htmlFor="newsletter">Subscribe to the newsletter</FieldLabel>
</Field>
</FieldGroup>
</FieldSet>2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
组件结构
Field
带标签、帮助文本和校验的单个控件。
Field
├── FieldLabel
├── Input / Textarea / Switch / Select
├── FieldDescription
└── FieldError2
3
4
5
FieldGroup
将相关字段放入同一组。需要时,在不同区块间使用 FieldSeparator。
FieldGroup
├── Field
│ ├── FieldLabel
│ ├── Input / Textarea / Switch / Select
│ ├── FieldDescription
│ └── FieldError
├── FieldSeparator
└── Field
├── FieldLabel
└── Input / Textarea / Switch / Select2
3
4
5
6
7
8
9
10
FieldSet
包含图例和描述的语义分组,通常包含一个 FieldGroup。
FieldSet
├── FieldLegend
├── FieldDescription
└── FieldGroup
├── Field
│ ├── FieldLabel
│ ├── Input / Textarea / Switch / Select
│ ├── FieldDescription
│ └── FieldError
└── Field
├── FieldLabel
└── Input / Textarea / Switch / Select2
3
4
5
6
7
8
9
10
11
12
结构解析
Field 系列用于构建无障碍表单。典型字段的结构如下:
<Field>
<FieldLabel htmlFor="input-id">Label</FieldLabel>
{/* Input, Select, Switch, etc. */}
<FieldDescription>Optional helper text.</FieldDescription>
<FieldError>Validation message.</FieldError>
</Field>2
3
4
5
6
Field是单个字段的核心容器。FieldContent是一个纵向 Flex 容器,用来组织标签和描述。没有描述时可省略。- 用
FieldGroup包裹相关字段,用FieldSet搭配FieldLegend进行语义分组。
表单
参阅表单文档,了解如何结合 Field 组件与 React Hook Form、Tanstack Form 或 Formisch 构建表单。
输入框
多行输入框
选择器
滑块
字段集
复选框
单选框
开关
选择卡片
在 FieldLabel 中包裹 Field 组件可创建可选字段组。适用于 RadioItem、Checkbox 和 Switch 组件。
字段组
用 FieldGroup 堆叠 Field 组件,并添加 FieldSeparator 进行分隔。
RTL
要在 shadcn/ui 中启用 RTL 支持,请参阅 RTL 配置指南。
响应式布局
- 纵向字段: 默认方向将标签、控件和帮助文本纵向排列,适合移动优先的布局。
- 横向字段: 在
Field上设置orientation="horizontal",让标签和控件并排排列。配合FieldContent可对齐描述。 - 响应式字段: 设置
orientation="responsive",在支持容器查询的父元素内自动切换列布局。在FieldGroup上应用@container/field-group类,在指定断点切换方向。
校验与错误
- 在
Field上添加data-invalid,让整个字段区块进入错误状态。 - 在输入控件本身添加
aria-invalid,供辅助技术识别。 - 将
FieldError紧接着控件渲染,或放在FieldContent内,使错误信息与字段对齐。
<Field data-invalid>
<FieldLabel htmlFor="email">Email</FieldLabel>
<Input id="email" type="email" aria-invalid />
<FieldError>Enter a valid email address.</FieldError>
</Field>2
3
4
5
无障碍
FieldSet和FieldLegend将相关控件分组,方便键盘和辅助技术用户使用。Field输出role="group",与FieldLabel和FieldLegend搭配使用时,嵌套控件可继承标签信息。- 适量使用
FieldSeparator,以便屏幕阅读器清楚区分各区块。
API 参考
FieldSet
渲染语义化 fieldset 并应用预设间距的容器。
| 属性 | 类型 | 默认值 |
|---|---|---|
className | string |
<FieldSet>
<FieldLegend>Delivery</FieldLegend>
<FieldGroup>{/* Fields */}</FieldGroup>
</FieldSet>2
3
4
FieldLegend
FieldSet 的图例元素。切换到 label 变体可与标签尺寸保持一致。
| 属性 | 类型 | 默认值 |
|---|---|---|
variant | "legend" | "label" | "legend" |
className | string |
<FieldLegend variant="label">Notification Preferences</FieldLegend>FieldLegend 有两种变体:legend 和 label。label 变体采用标签的尺寸和对齐方式,适合嵌套的 FieldSet。
FieldGroup
用于堆叠 Field 组件的布局容器,并启用容器查询以实现响应式排列。
| 属性 | 类型 | 默认值 |
|---|---|---|
className | string |
<FieldGroup className="@container/field-group flex flex-col gap-6">
<Field>{/* ... */}</Field>
<Field>{/* ... */}</Field>
</FieldGroup>2
3
4
Field
单个字段的核心容器,提供方向控制、无效状态样式和间距。
| 属性 | 类型 | 默认值 |
|---|---|---|
orientation | "vertical" | "horizontal" | "responsive" | "vertical" |
className | string | |
data-invalid | boolean |
<Field orientation="horizontal">
<FieldLabel htmlFor="remember">Remember me</FieldLabel>
<Switch id="remember" />
</Field>2
3
4
FieldContent
标签位于控件旁边时,用纵向 Flex 容器将控件与描述分组。没有描述时可省略。
| 属性 | 类型 | 默认值 |
|---|---|---|
className | string |
<Field>
<Checkbox id="notifications" />
<FieldContent>
<FieldLabel htmlFor="notifications">Notifications</FieldLabel>
<FieldDescription>Email, SMS, and push options.</FieldDescription>
</FieldContent>
</Field>2
3
4
5
6
7
FieldLabel
适用于直接输入控件和嵌套 Field 子项的标签样式。
| 属性 | 类型 | 默认值 |
|---|---|---|
className | string |
<FieldLabel htmlFor="email">Email</FieldLabel>FieldTitle
在 FieldContent 中渲染带标签样式的标题。
| 属性 | 类型 | 默认值 |
|---|---|---|
className | string |
<FieldContent>
<FieldTitle>Enable Touch ID</FieldTitle>
<FieldDescription>Unlock your device faster.</FieldDescription>
</FieldContent>2
3
4
FieldDescription
帮助文本插槽,在横向布局中自动平衡较长文本的换行。
| 属性 | 类型 | 默认值 |
|---|---|---|
className | string |
<FieldDescription>We never share your email with anyone.</FieldDescription>FieldSeparator
用于分隔 FieldGroup 内部区块的视觉分隔线,可接收可选的行内内容。
| 属性 | 类型 | 默认值 |
|---|---|---|
className | string |
<FieldSeparator>Or continue with</FieldSeparator>FieldError
无障碍错误容器,可接收子元素或 errors 数组(例如来自 react-hook-form 的错误)。
| 属性 | 类型 | 默认值 |
|---|---|---|
errors | Array<{ message?: string } | undefined> | |
className | string |
<FieldError errors={errors.username} />errors 数组中有多条消息时,组件会自动渲染为列表。
FieldError 也支持任何实现 Standard Schema 的校验器所产生的问题信息,包括 Zod、Valibot 和 ArkType。直接传入 schema 校验结果中的 issues 数组,即可统一渲染来自不同库的错误列表。