我遇到了将 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/