簡體   English   中英

Typescript 具有多個道具類型的 React 功能組件

[英]Typescript React Functional Component With Multiple Props Type

我正在使用 react "react": "^17.0.0", function 組件來傳遞這樣的參數:

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

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

但我仍然想通過使用如下道具將另一個參數傳遞到 function 組件中:

<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 || {}}
      />

我已經定義了這樣的道具:

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

我應該怎么做才能將這兩個參數傳遞給 function 組件? 是否可以將兩個參數傳遞給組件?

要在同一組件上使用這兩種類型,您可以使用UpdateFormProps類型擴展RoleProps接口。 像這樣的

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

現在你可以像這樣使用UpdateFormProps中的道具

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

如果您想確保傳遞接口RoleProps的所有道具或類型UpdateFormProps的所有道具,那么您可以這樣做:

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM