Home > Mobile >  Typescript React Functional Component With Multiple Props Type
Typescript React Functional Component With Multiple Props Type

Time:04-17

I am using react "react": "^17.0.0", function component to pass parameter like this:

interface RoleProps {
  roles: IRoleState
  dispatch: Dispatch
  roleListLoading: boolean
}

const EditPermission: React.FC<RoleProps> = ({roles, dispatch, roleListLoading}) => {
}

but I still want to pass another parameter into the function component by using props like this:

<EditPermission
        onSubmit={async (value) => {
          if(!currentRow){
            return
          }
          const success = await handleUpdate(value,currentRow.id);
          if (success) {
            handleUpdateModalVisible(false);
            setCurrentRow(undefined);
            if (actionRef.current) {
              actionRef.current.reload();
            }
          }
        }}
        onCancel={() => {
          handleUpdateModalVisible(false);
          setCurrentRow(undefined);
        }}
        updateModalVisible={editPermissionModalVisible}
        values={currentRow || {}}
      />

I have alredy define the props like this:

export type UpdateFormProps = {
  onCancel: (flag?: boolean, formVals?: FormValueType) => void;
  onSubmit: (values: FormValueType) => Promise<void>;
  updateModalVisible: boolean;
  values: Partial<API.InterviewListItem>;
};

what should I do to pass both parameter into the function component? is it possible to pass both parameter into component?

CodePudding user response:

To use both types on the same component, you can extend RoleProps interface with UpdateFormProps type. something like this

interface RoleProps extends UpdateFormProps {
  roles: IRoleState
  dispatch: Dispatch
  roleListLoading: boolean
}

Now you can use the props from UpdateFormProps like this

const EditPermission: React.FC<RoleProps> = ({roles, dispatch, roleListLoading, onCancel, onSubmit, updateModalVisible, values}) => {
  //
}

CodePudding user response:

If you want to make sure that you pass all the props of the interface RoleProps OR all the props of the type UpdateFormProps then you can do this:

const EditPermission: React.FC<RoleProps | UpdateFormProps> = ...
  • Related