English 中文(简体)
• 如何在14个字典和反应型照相中形成一个通用表格?
原标题:How to Create a Generic Form Component in Next.js 14 with TypeScript and react-hook-form?

< Question:

I m 从事以下工作:13项使用原型,Im 试图采用反应照相方式创建通用成分。 目标是有一个单一形式的组成部分,能够处理不同类型的形式,如报告、客户和用户。 每一种形式都有自己的一套领域,但形式业务(休假、重新设置、更新和删除)在所有类型上都保持相同。

这里,我试图做到的简略版本是:

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>
  );
};

问题:

Im 面临一个在通用语种内进行原型检查的问题。 由于反应照像要求准确打造形式领域,我只能使用一种联盟类型来收集我的形式数据。 然而,我需要通用表格部分根据所提供的表格接受不同类型的初步数据。

I m 无法保证如何在通用名称部分内妥善处理类型检查和有条件提供,以顾及不同类型的形式数据,同时保持类型安全。

Expected Output:

我期望有一个单一的通用部分,能够处理不同类型的形式,从而根据所提供的初步数据类型,使适当的领域成为可能。 此外,我需要确保在构成部分内适当处理原型检查。

问题回答

I would make GenericForm take a generic argument.

如此界定构成部分。

const GenericForm: = <T>> 数据:FormProps<T>{

然后使用这一编号:<GenericForm<ReportFormData> initialData={report Field:>> >submit={()=>

That should make GenericForm have type safe initialData and onSubmit





相关问题
store data in memory with nestjs

I am trying to persist some data in my nestjs server so I can then use that data in my client app through http requests. I have created a products.service.ts file with the function getAllData() that ...

React Hook Form Error on custom Input component

I am having a problem when I use react hook form + zod in my application, in short the inputs never change value and I get the following error in the console: Warning: Function components cannot be ...

Updatable promises using proxy in JavaScript

EDIT: I ve updated this question, and the old question is moved here. A POC can be found on this jsfiddle or the snippet below GOAL: The goal here is to make or rather simulate a promise that can be ...

热门标签