如何使用react-hook-form与shadcn设置输入框值并填充编辑数据
如何在shadcn表单中从props初始化/同步输入框值
shadcn的表单基于react-hook-form实现,表单状态由react-hook-form统一管理,不能直接通过原生value属性赋值,需要借助其提供的API来处理props值的同步:
1. 初始化时设置默认值
如果组件挂载时props已经携带了需要展示的内容,直接在useForm的defaultValues中传入props值即可:
import { useForm } from 'react-hook-form'; import { Textarea } from '@/components/ui/textarea'; interface BlogFormProps { content?: string; onSubmit: (data: { content: string }) => void; } export function BlogForm({ content, onSubmit }: BlogFormProps) { // 用props.content作为表单初始值 const { register, handleSubmit } = useForm({ defaultValues: { content: content || '' } }); return ( <form onSubmit={handleSubmit(onSubmit)}> <Textarea {...register('content')} placeholder="编写博客内容" /> <button type="submit">提交</button> </form> ); }
2. 动态同步props更新的值
如果props中的content是异步获取(比如编辑时从后端加载数据),需要监听props变化,调用setValue同步表单字段:
import { useForm, useEffect } from 'react-hook-form'; import { Textarea } from '@/components/ui/textarea'; interface BlogFormProps { content?: string; onSubmit: (data: { content: string }) => void; } export function BlogForm({ content, onSubmit }: BlogFormProps) { const { register, handleSubmit, setValue } = useForm({ defaultValues: { content: content || '' } }); // 监听content props变化,实时同步到表单 useEffect(() => { if (content !== undefined) { setValue('content', content); } }, [content, setValue]); return ( <form onSubmit={handleSubmit(onSubmit)}> <Textarea {...register('content')} placeholder="编写博客内容" /> <button type="submit">提交</button> </form> ); }
3. 使用Controller组件的场景
如果需要更精细地控制表单字段(比如自定义校验、处理复杂组件),可以用Controller包裹shadcn组件:
import { useForm, Controller } from 'react-hook-form'; import { Textarea } from '@/components/ui/textarea'; interface BlogFormProps { content?: string; onSubmit: (data: { content: string }) => void; } export function BlogForm({ content, onSubmit }: BlogFormProps) { const { control, handleSubmit, setValue } = useForm({ defaultValues: { content: content || '' } }); useEffect(() => { if (content !== undefined) { setValue('content', content); } }, [content, setValue]); return ( <form onSubmit={handleSubmit(onSubmit)}> <Controller name="content" control={control} render={({ field }) => ( <Textarea {...field} placeholder="编写博客内容" /> )} /> <button type="submit">提交</button> </form> ); }
核心逻辑:shadcn表单的状态完全由react-hook-form管理,所有值的设置、更新都需要通过其提供的defaultValues(初始化)或setValue(动态更新)API完成,不能直接操作组件的value属性。
内容的提问来源于stack exchange,提问作者Zheng Jiawen
相关产品推荐
相关产品推荐

