Question:
我正在使用TypScript开发Next.js 13应用程序,并且我正在try 使用react-hook-form创建一个通用表单组件.目标是拥有一个可以处理不同类型表单(例如报表、客户端和用户)的单一表单组件.每种类型的表单都有自己的一组字段,但表单操作(保存、重置、更新、删除)在所有类型中保持相同.
这是我试图实现的目标的简化版本:
import { FC } from 'react';
import { useForm, SubmitHandler } from 'react-hook-form';
// Define different types of form data
type ReportFormData = {
reportField: string;
};
type ClientFormData = {
clientField: string;
};
type UserFormData = {
userField: string;
};
// Define props for the generic form component
type FormProps<T> = {
initialData: T;
onSubmit: SubmitHandler<T>;
};
// Create the generic form component
const GenericForm: FC<FormProps> = ({ initialData, onSubmit }) => {
const { register, handleSubmit, reset } = useForm({
defaultValues: initialData,
});
const onSubmitHandler: SubmitHandler<T> = (data) => {
onSubmit(data);
};
return (
<form onSubmit={handleSubmit(onSubmitHandler)}>
{/* How can I conditionally render fields based on the type of data? */}
{/* How to properly handle type checking in this scenario? */}
{/* Placeholder for save operation */}
<button type="submit">Save</button>
{/* Placeholder for reset operation */}
<button type="button" onClick={() => reset(initialData)}>
Reset
</button>
{/* Placeholder for update operation */}
{/* Placeholder for delete operation */}
</form>
);
};
问题 :
我面临着GenericForm组件内的TypScript类型判断问题.由于react-hook-form需要对表单字段进行精确的输入,因此我不能简单地对表单数据使用联合类型.然而,我需要GenericForm组件根据所呈现的表单接受不同类型的初始数据.
我不确定如何正确处理GenericForm组件内的类型判断和条件呈现,以适应不同类型的表单数据,同时保持类型安全.
预期yields :
我希望拥有一个单一的GenericForm组件,它可以处理不同类型的表格,并根据提供的初始数据类型呈现适当的字段.此外,我需要确保在组件内正确处理TypScript类型判断.