reactjs - React Typescript FunctionComponent 不分配函数

标签 reactjs 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) => {....} ),但是在代码中上面没有分配,也没有分配任何功能。它是如何工作的?

最佳答案

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

tl;博士

'declare' is used to tell the compiler 'this thing (usually a variable) exists already, and therefore can be referenced by other code, also there is no need to compile this statement into any JavaScript"

当引用SO


docs:

Declaration.

Use declare var to declare variables. If the variable is read-only, you can use declare const. You can also use declare let if the variable is block-scoped.

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

FormWithRedirect 是一个声明,描述如何使用/返回 const。即它将是一个具有 FormWithRedirectProps

的功能组件

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

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


示例:

而不是将 const 与赋值耦合

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

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

declare const FormWithRedirect: FC<RedirectWithProps>

预计在其他地方实现

const FormWithRedirect = () => {}

关于reactjs - React Typescript FunctionComponent 不分配函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64665724/

相关文章:

reactjs - 使用 Material UI 进行主题嵌套

javascript - ' promise <void >' is not assignable to type ' promise <IListItem[]>

javascript - 密码确认和密码相同,但验证仍然触发 React 组件中的 JOI

reactjs - 如何动态更改 React Native 堆栈导航屏幕的标题?

javascript - react 教程 : state not working

angular - 暂停和恢复可观察流,请提出更好的选择

typescript - 是否可以在 TypeScript 中定义 string.Empty?

javascript - Angular 4 innerHTML 属性删除 id 属性

javascript - 使用 react-daterange-picker "No overload matches this call." typescript 错误

javascript - 如何从 react-semantic-ui 中的多个搜索选择下拉框中获取值?