基本信息
- 类型: React 组件 (shadcn/ui)
- 路径:
./src/components/ui/form.tsx
功能描述
表单组件,基于 react-hook-form 提供完整的表单解决方案。支持字段验证、错误显示、标签关联等功能。
导出内容
Form - 表单提供者(FormProvider)
FormField - 字段控制器
FormItem - 表单项容器
FormLabel - 表单标签
FormControl - 表单控件包装器
FormDescription - 字段描述
FormMessage - 错误消息
useFormField - 表单字段 Hook
Props 接口
| 属性 | 类型 | 必填 | 默认值 | 说明 |
| name | string | 是 | - | 字段名称 |
| control | Control<T> | 是 | - | react-hook-form 控制对象 |
| render | ({ field, fieldState, formState }) => React.ReactNode | 是 | - | 渲染函数 |
| 属性 | 类型 | 必填 | 默认值 | 说明 |
| className | string | 否 | - | 自定义CSS类名 |
| ...props | React.ComponentProps<'div'> | 否 | - | div属性 |
| 属性 | 类型 | 必填 | 默认值 | 说明 |
| className | string | 否 | - | 自定义CSS类名 |
| ...props | React.ComponentProps<typeof LabelPrimitive.Root> | 否 | - | Label属性 |
| 属性 | 类型 | 必填 | 默认值 | 说明 |
| ...props | React.ComponentProps<typeof Slot> | 否 | - | Slot属性 |
依赖
react-hook-form - 表单管理库
@radix-ui/react-label - Radix UI 标签原语
@radix-ui/react-slot - 插槽组件
@/lib/utils - 工具函数 (cn)
@/components/ui/label - 标签组件
使用示例
import { useForm } from "react-hook-form";
import { zodResolver } from "@hookform/resolvers/zod";
import * as z from "zod";
import {
Form,
FormControl,
FormDescription,
FormField,
FormItem,
FormLabel,
FormMessage,
} from "@/components/ui/form";
import { Input } from "@/components/ui/input";
import { Button } from "@/components/ui/button";
const formSchema = z.object({
username: z.string().min(2, "用户名至少需要2个字符"),
email: z.string().email("请输入有效的邮箱地址"),
});
function ProfileForm() {
const form = useForm<z.infer<typeof formSchema>>({
resolver: zodResolver(formSchema),
defaultValues: {
username: "",
email: "",
},
});
return (
<Form {...form}>
<form onSubmit={form.handleSubmit(onSubmit)} className="space-y-8">
<FormField
control={form.control}
name="username"
render={({ field }) => (
<FormItem>
<FormLabel>用户名</FormLabel>
<FormControl>
<Input placeholder="请输入用户名" {...field} />
</FormControl>
<FormDescription>这是您的公开显示名称。</FormDescription>
<FormMessage />
</FormItem>
)}
/>
<Button type="submit">提交</Button>
</form>
</Form>
);
}