如何使用 TypeScript 和 React-hook-form 在 Next.js 14 中创建通用表单组件?

问题描述 投票:0回答:1

问题:

我正在使用 TypeScript 开发 Next.js 13 应用程序,并尝试使用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 组件中面临 TypeScript 类型检查的问题。由于react-hook-form需要对表单字段进行精确输入,因此我不能简单地对表单数据使用联合类型。但是,我需要 GenericForm 组件来根据呈现的表单接受不同类型的初始数据。

我不确定如何在 GenericForm 组件中正确处理类型检查和条件渲染,以适应不同类型的表单数据,同时保持类型安全。

预期输出:

我希望有一个 GenericForm 组件可以处理不同类型的表单,根据提供的初始数据的类型呈现适当的字段。此外,我需要确保在组件内正确处理 TypeScript 类型检查。

typescript typescript-typings typescript-generics react-hook-form next.js14
1个回答
0
投票

我会让

GenericForm
采用通用参数。

像这样输入组件。

const GenericForm:  = <T,>({ initialData, onSubmit }:FormProps<T>) => {

那就这样使用吧

<GenericForm<{id:string | null, name:string | null, age: number| null}> initialDate={{...myinitialData} onSubmit={()=>{}}> 

这应该使 GenericForm 具有类型安全

initialData
onSubmit

© www.soinside.com 2019 - 2024. All rights reserved.