通用反应组件道具

时间:2020-09-06 23:41:51

标签: reactjs typescript typescript-generics react-component

我正在使用带有'fieldStructures'和'onSubmit'道具的打字稿在React中构建表单组件。

type FieldStructure {
    type: 'text';
    name: string;
    label?: string;
    helpText?: string;
    required?: boolean;
    multiline?: boolean;
} | {
    type: 'date';
    name: string;
    label?: string;
    helpText?: string;
    required?: boolean;
} | {
    type: 'option';
    name: string;
    label?: string;
    helpText?: string;
    required?: boolean;
    options: string[];
    multi?: boolean;
} | {
    type: 'file';
    name: string;
    label?: string;
    helpText?: string;
    required?: boolean;
    fileTypes?: string[];
}

type FieldValue <T extends FieldType = any> =
    T extends 'text' ? string
    : T extends 'date' ? Date | null
    : T extends 'option' ? string | string[] | null
    : T extends 'file' ? string | File | null
    : string | string[] | Date | File | null

interface FormModalProps {
    fieldStructures: FieldStructure[];
    handleSubmit: (values: { [key: string]: FieldValue }) => void | Promise<void>;
}

export const FormModal: React.FC<FormModalProps> = ({
    fieldStructures,
    handleSubmit
}) => { ... }

这对于仅制造组件非常有用,但对于使用它却不那么有用。我希望values参数的类型取决于像这样传递给fieldStructures参数的内容...

interface FormValues <T extends FieldStructure[]> {
    //keys are the names of each field structure
    //values are FieldValue<field structure type>
}

interface FormModalProps <T extends FieldStructure[]> {
    fieldStructures: T;
    handleSubmit: (values: FormValues<T>) => void | Promise<void>;
}

这个例子感觉有点过分简化,但是有人知道实现相同结果的方法吗?

完整的代码可以在我的github上找到: https://github.com/baldwin-design-co/bdc-components/blob/master/src/form%20modal/form-modal.tsx

1 个答案:

答案 0 :(得分:1)

您应该为每个结构指定一个类型,该类型可以扩展具有指定属性的通用类型(在您的情况下为type)。 然后,对于每种形式,您都需要接收一个扩展了公共配置的配置。 FormValue比将是一个简单的keyof T

在下面检查此示例:

// Field types

export interface FieldStructure {
    type: 'text' | 'date';
}

export interface TextField extends FieldStructure {
    type: 'text';
    label: string;
}

export interface DateField extends FieldStructure {
    type: 'date';
    label: string;
}

// Calculate the value based on field type

export type FieldValue<T extends FieldStructure> = 
    T extends TextField ? string
    : T extends DateField ? Date | null
    : string | Date | null ;
    
// Types the form itself

type FormConfig = {[key: string]: FieldStructure}

// Gets the form value based on the type of each field
type FormValue<T extends FormConfig> = {
    [k in keyof T]: FieldValue<T[k]>
}


// Example of usage:

interface MyFormConfig extends FormConfig {
   a: TextField;
   b: DateField
}