用途:React Hook Form 用于在 React 中构建高性能、灵活的表单,特点是校验简单、重渲染最少。
主要能力:提供 useForm Hook,包含 register、handleSubmit、watch、formState、reset、setValue、getValues、trigger、control 等。支持同步与异步校验(required、pattern、min、max、minLength、maxLength、validate),错误信息展示,表单状态(errors、isDirty、isValid、isSubmitting、isSubmitted、isSubmitSuccessful、submitCount、dirtyFields、touchedFields)。支持 useFieldArray 处理动态字段数组,Controller 集成受控组件(如 MUI、Radix、自定义输入),以及 watch 监听字段变化。
使用方式:安装 npm install react-hook-form。基础用法通过 useForm 获取 register 与 handleSubmit,将 register 展开到 input 上并传入校验规则,用 formState.errors 显示错误。schema 集成需安装 npm install @hookform/resolvers zod,使用 zodResolver。错误消息组件需安装 npm install @hookform/error-message。可与 Next.js Server Action、shadcn/ui Form 配合使用。
适用场景:登录、注册、资料编辑、动态表单、需要 schema 校验或与 UI 组件库集成的 React 表单。
限制与建议:资料建议设置 defaultValues 避免 undefined,使用 Zod 获得类型安全,对 UI 库使用 Controller,谨慎使用 watch 以减少重渲染,提交时显示加载状态并禁用表单。常见错误包括缺少 name 属性、数组未使用 field.id 作为 key、直接修改值而非使用 setValue/reset、每次按键都校验、未显示错误信息。具体版本、收费与平台支持暂未提供。