简体   繁体   中英

How to pass prop to a component using React and typescript?

Hi there is a component FormField and that accepts either of one icon create or edit. Now I use this FormField within another component SelectWithFormField

Like so:

const FormField = ({create, edit}: FormFieldProps) => {
    const iconTooltip = create ? {create}: edit ? {edit} : undefined;
    return (
        <Label {...iconTooltip} />
    );
}

const SelectWithFormField = <T1, T2>) =>  (
    <FormField //error here
        create={create}
        edit={edit}
    />
);

This SelectWithFormField will be called by other components where one will be called with edit and other with Create. I want to do so such that I can use SelectWithFormField with edit icon in some pages and with create icon in other pages.

const Main1 = () => {
    <SelectWithFormField edit={edit} />
}

const Main2 = () => {
    <SelectWithFormField create={create} />
}

But since FormField accepts either of create or edit props I am not able to pass 2 props together in SelectFormField component. How can I fix this. could someone help me with this. thanks.

EDIT:

type FormFieldProps = {
    fieldId: string;
} & IconTooltipProps;

type IconTooltipProps = EditTooltipProps | CreateTooltipProps;

type EditTooltipProps = {
    create?: never;
    edit?: string;
}

type CreateTooltipProps = {
    create?: string;
    edit?: never;
}

What about something like this?

interface CreateTooltipProps {
    create: string;
    edit?: string;
}

interface EditTooltipProps {
    edit: string;
}

type IconTooltipProps = CreateTooltipProps | EditTooltipProps;

If you pass create as a prop, edit is optional. If create is not passed, edit is required.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM