表单 Form
本组件为 React 表单管理提供了一整套支持。通过结合 react-hook-form
和 Radix UI
,可以高效构建表单,同时提供动态验证与错误提示。
📦 引入方式
import { Form, FormControl, FormField, FormItem, FormLabel, FormMessage } from '@npmqg/react-ui-form';
🧩 使用示例
📚 基本表单
- 示例
- 源码
import { Smartphone } from "lucide-react";
import React from "react";
import { useForm } from "react-hook-form";
import { Button, Input } from "@npmqg/react-ui-core";
import {
Form,
FormControl,
FormField,
FormItem,
FormLabel,
FormMessage,
} from "@npmqg/react-ui-form";
export default function FormIndex() {
const form = useForm({
defaultValues: {
account: "",
},
mode: "onChange", // 可以是 'onChange'、'onSubmit' 等
});
//表单提交事件
const onSubmit = (values) => {
alert("触发提交" + JSON.stringify(values));
};
return (
<Form {...form}>
<form
className="space-y-6 flex flex-col h-full w-1/2 bg-section rounded-md p-4"
onSubmit={form.handleSubmit(onSubmit)}
>
<FormField
control={form.control}
name="account"
render={({ field }) => (
<FormItem>
<FormLabel>手机号</FormLabel>
<FormControl>
<Input
maxLength={20}
placeholder="请输入手机号"
prefix={<Smartphone size={20} />}
{...field}
/>
</FormControl>
<FormMessage />
</FormItem>
)}
rules={{
required: "请输入手机号",
pattern: {
value: /^1\d{10}$/,
message: "请输入有效的手机号",
},
}}
/>
<Button className="w-full">登录</Button>
</form>
</Form>
);
}
📦 组件 API
组件名 | 描述 | 主要 Props(类型 - 说明) |
---|---|---|
Form | 封装自 FormProvider ,用于提供表单上下文 | ...formProps :来自 react-hook-form 的属性 |
FormField | 封装 Controller ,用于管理单个字段 | name (string ) - 字段名control (Control ) - 控制器对象render (function ) - 渲染函数 |
FormLabel | 表单字段的标签,自动关联对应控件 | htmlFor (string ) - 绑定控件 IDclassName (string ) - 样式类 |
FormControl |