首页 > 解决方案 > 在不分配功能的情况下反应 Typescript FunctionalComponent

问题描述

我遇到了用于定义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) => {....}),但是在上面的代码中没有分配,也没有分配函数。它是如何工作的?

标签: reactjstypescript

解决方案


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

tl;博士

'declare' 用于告诉编译器“这个东西(通常是一个变量)已经存在,因此可以被其他代码引用,也不需要将这个语句编译成任何 JavaScript”

引用SO时


文档中:

宣言。

使用 declare var 来声明变量。如果变量是只读的,则可以使用 declare const。如果变量是块范围的,您也可以使用 declare let。

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

FormWithRedirect是一个描述如何使用/返回 const 的声明。即它将是一个功能组件FormWithRedirectProps

这是定义特定变量将接受/返回的接口/类型的简写。

据我了解,使用 declare 是编译器的简写:1. 不显式创建实例的定义FormWithRedirect2. 稍后引用FormWithRedirect类型推断(在实现 const 之前)


例子:

而不是将 const 与赋值耦合

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

某个地方,(声明 FormWithRedirect将并且应该存在于某处)

declare const FormWithRedirect: FC<RedirectWithProps>

期待在其他地方实施

const FormWithRedirect = () => {}

推荐阅读