【问题标题】:React Typescript FunctionalComponent without assigning function在不分配功能的情况下反应 Typescript FunctionalComponent
【发布时间】:2021-02-16 07:13:20
【问题描述】:

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

【问题讨论】:

  • 试图解释如下:

标签: reactjs typescript


【解决方案1】:

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

tl;dr

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

引用SO


docs:

声明。

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

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

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

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

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


示例:

而不是将 const 与赋值耦合

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

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

declare const FormWithRedirect: FC<RedirectWithProps>

期待在别处实施

const FormWithRedirect = () => {}

【讨论】:

    猜你喜欢
    • 2017-12-14
    • 1970-01-01
    • 2014-05-23
    • 1970-01-01
    • 2017-09-19
    • 1970-01-01
    • 2019-10-31
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多