TypeScript与react-hook-form类型不兼容:UseFormRegister赋值报错求助
解决react-hook-form传递register时的类型不匹配警告
问题原因
父组件通过useForm<AppointmentProps>生成的register类型为UseFormRegister<AppointmentProps>,但子组件AppointmentForm的props中把register定义成了默认的UseFormRegister<FieldValues>,TypeScript判定这两种类型不兼容,因此抛出警告。
解决方案
1. 修正types.ts中的AppointmentFormProps接口
给register字段指定与父组件一致的泛型类型,绑定AppointmentProps:
import { UseFormRegister } from "react-hook-form"; import { AppointmentProps } from "./types"; export interface AppointmentFormProps { register: UseFormRegister<AppointmentProps>; // 其他需要传递的props字段 }
2. 确认父组件Appointment.tsx的useForm泛型配置
保证父组件中useForm的泛型参数是AppointmentProps:
import { useForm } from "react-hook-form"; import { AppointmentProps } from "./types"; import AppointmentForm from "./AppointmentForm"; export default function Appointment() { const { register } = useForm<AppointmentProps>(); return ( <form> <AppointmentForm register={register} /> </form> ); }
3. 子组件AppointmentForm.tsx正确接收props
直接使用定义好的AppointmentFormProps作为props类型:
import { AppointmentFormProps } from "./types"; export default function AppointmentForm({ register }: AppointmentFormProps) { return ( <div> {/* 这里的fieldName必须是AppointmentProps中已定义的字段 */} <input {...register("fieldName")} /> </div> ); }
通用化组件扩展方案
如果希望AppointmentForm支持任意表单类型,可以改为泛型组件:
// types.ts import { UseFormRegister, FieldValues } from "react-hook-form"; export interface AppointmentFormProps<T extends FieldValues> { register: UseFormRegister<T>; } // AppointmentForm.tsx import { AppointmentFormProps } from "./types"; export default function AppointmentForm<T extends FieldValues>({ register }: AppointmentFormProps<T>) { return ( <input {...register("fieldName")} /> ); } // 父组件中使用时指定泛型 <AppointmentForm<AppointmentProps> register={register} />
内容的提问来源于stack exchange,提问作者Stykgwar
相关产品推荐
相关产品推荐

