如何解决React中的ForwardRefExoticComponent和ForwardRefRenderFunction有什么区别?
我正在编写一个React组件,该组件可以将ref转发给它的孩子
我发现对于功能组件的返回类型,我可以使用 ForwardRefExoticComponent 和 ForwardRefRenderFunction 。但是我不确定它们之间有什么区别。
到目前为止,当使用 ForwardRefExoticComponent 时,我可以扩展它,而 ForwardRefRenderFunction 不能?我在这里发布了一个与我的案子有关的问题:How to export forwardRef with ForwardRefRenderFunction
如果有人知道他们之间的区别以及他们所做的事情,请帮助我。因为似乎React团队没有关于它们的文档(但是它们在react包中)
解决方法
ForwardRefExoticComponent
取自here的定义是
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
取自here的定义是
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
还有一个类型为$$typeof
的成员symbol
-
ForwardRefRenderFunction
的电话签名使用props
对象,该对象必须包含成员children
和ref对象作为参数,而ForwardRefExoticComponent
的电话签名仅使用一个任意形状的道具对象作为参数。
更多想法
这两个定义的相互作用最好在definition of the forwardRef
function中看到:
function forwardRef<T,P = {}>(render: ForwardRefRenderFunction<T,P>): ForwardRefExoticComponent<PropsWithoutRef<P> & RefAttributes<T>>;
此外,这两个定义之间的巨大差异似乎是ForwardRefExoticComponent
(像所有外来组件一样)不是函数组件,而是实际上只是对象,在呈现它们时会对其进行特殊处理。因此,评论
注意:外部组件不可调用。
由于某些原因,在某些地方,这些奇特的组件是必需的。
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。