網站搜尋

reactjs - React Typescript 函數式組件而不指定函數


我碰到這段用於將 FormWithRedirect 定義為 FC(FunctionComponent) 的程式碼:

declare const FormWithRedirect: FC<FormWithRedirectProps>;
export declare type FormWithRedirectProps = FormWithRedirectOwnProps & Omit<FormProps, 'onSubmit' | 'active'>;
export interface FormWithRedirectOwnProps {
  defaultValue?: any;
  record?: Record;
  redirect?: RedirectionSideEffect;
  render: (props: Omit<FormViewProps, 'render' | 'setRedirect'>) => React.ReactElement<any, any>;
  ...
}

而這就是它的使用方式:

const SimpleForm: FC<SimpleFormProps> = (props) => (
  <FormWithRedirect {...props} render={(formProps) => <SimpleFormView {...formProps} />} />
);

考慮到下列對 FC 的定義:

type FC<P = {}> = FunctionComponent<P>;

interface FunctionComponent<P = {}> {
    (props: PropsWithChildren<P>, context?: any): ReactElement | null;
    propTypes?: WeakValidationMap<P>;
    contextTypes?: ValidationMap<any>;
    defaultProps?: Partial<P>;
    displayName?: string;
}

我想在使用 FormWithRedirect 之前應該要有賦值(類似 FormWithRedirect=(props) => {....}),然而在上面的程式碼中沒有賦值,也沒有函數被賦給它。它是如何運作的?

答案#1

https://stackoverflow.com/a/59552002/2312051

簡而言之

「declare」用來告訴編譯器「這個東西(通常是變數)已經存在,因此可以被其他程式碼引用,而且不需要將這個語句編譯成任何 JavaScript」

當提到 SO 時


在文件中:

宣言。

使用 declare var 來宣告變數。如果變數是唯讀的,你可以使用 declare const。如果變數是區塊作用域的,你也可以使用 declare let。

/** The number of widgets present */
declare var foo: number;

FormWithRedirect 是一個聲明,用來描述 const 將如何被使用或返回。也就是說,它將是一個帶有 FormWithRedirectProps 的功能性組件。

這是一種簡寫,用於定義特定變數將接受/返回的介面/類型。

據我理解,使用 declare 是對編譯器的一種簡寫,作用是 1. 不明確為 FormWithRedirect 的實例創建定義,以及 2. 在稍後(在你實現 const 之前)引用 FormWithRedirect 的類型推斷


範例:

而不是將 const 與賦值綁定

const FormWithRedirect: FC<FormWithRedirectProps> = () => {
  ...whatever
}

某個地方,(聲明 FormWithRedirect 將會且應該存在 在某處)

declare const FormWithRedirect: FC<RedirectWithProps>

預期在其他地方實現

const FormWithRedirect = () => {}