我正在编写一个React组件,它可以将ref转发给它的后代
我发现对于函数组件的返回类型,我可以使用ForwardRefExoticComponent和ForwardRefRenderFunction.。但我不知道他们之间有什么区别。
到目前为止,当使用ForwardRefExoticComponent,时,我可以扩展它,而ForwardRefRenderFunction不能吗?我在这里发布了一个与我的案例相关的问题:如何用forwardRef导出ForwardRefRenderFunction
如果有人知道他们之间的区别和他们做什么,请帮助我。因为React团队似乎没有关于他们的文档(但是他们在react包中)
发布于 2020-10-07 07:19:30
ForwardRefExoticComponent
取自这里的定义是
interface ExoticComponent<P = {}> {
/**
* **NOTE**: Exotic components are not callable.
*/
(props: P): (ReactElement|null);
readonly $$typeof: symbol;
}
interface NamedExoticComponent<P = {}> extends ExoticComponent<P> {
displayName?: string;
}
interface ForwardRefExoticComponent<P> extends NamedExoticComponent<P> {
defaultProps?: Partial<P>;
propTypes?: WeakValidationMap<P>;
}
如果你把它写出来,你会得到
interface ForwardRefExoticComponent<P> {
/**
* **NOTE**: Exotic components are not callable.
*/
(props: P): (ReactElement|null);
readonly $$typeof: symbol;
displayName?: string;
defaultProps?: Partial<P>;
propTypes?: WeakValidationMap<P>;
}
ForwardRefRenderFunction
取自这里的定义是
interface ForwardRefRenderFunction<T, P = {}> {
(props: PropsWithChildren<P>, ref: ((instance: T | null) => void) | MutableRefObject<T | null> | null): ReactElement | null;
displayName?: string;
// explicit rejected with `never` required due to
// https://github.com/microsoft/TypeScript/issues/36826
/**
* defaultProps are not supported on render functions
*/
defaultProps?: never;
/**
* propTypes are not supported on render functions
*/
propTypes?: never;
}
差异
ForwardRefRenderFunction
不支持propTypes
和defaultProps
,而ForwardRefExoticComponent
支持。ForwardRefExoticComponent
有一个类型为symbol
的附加成员$$typeof
。ForwardRefRenderFunction
的调用签名使用一个props
对象,该对象必须包括一个成员children
和一个ref对象作为参数,而ForwardRefExoticComponent
的调用签名只以任意形状的支持对象作为参数。更多的想法
这两个定义的相互作用最好在函数中看到。
function forwardRef<T, P = {}>(render: ForwardRefRenderFunction<T, P>): ForwardRefExoticComponent<PropsWithoutRef<P> & RefAttributes<T>>;
另外,这两个定义之间的一个很大的区别似乎是,ForwardRefExoticComponent
(和所有外来组件一样)不是函数组件,实际上只是对象,在呈现它们时会特别处理它们。因此,评论
注意到:外来组件是不可调用的。
出于某种原因,这些奇特的部件在某些地方是必要的。
https://stackoverflow.com/questions/64237804
复制相似问题