reactjs - 如何为 ForwardRefExoticComponent 添加静态道具类型
问题描述
我有一个FC ,Modal
我需要向它添加两个静态方法。我不知道如何为组件添加类型。这样我就可以在不使用类型断言的情况下直接分配和分配给。show
hide
ModalStaticProps
show
hide
Modal
import React, { ReactNode, RefAttributes } from 'react';
interface ModalProps {
title: ReactNode;
}
interface ModalStaticProps {
show(): void;
hide(): void;
}
const Modal: React.ForwardRefExoticComponent<ModalProps & RefAttributes<HTMLDivElement>> = React.forwardRef<
HTMLDivElement,
ModalProps
>(({ title }: ModalProps, ref) => {
return <div ref={ref}>{title}</div>;
});
// I want to this after add `ModalStaticProps` type
// Modal.show = () => { };
// Modal.hide = () => { };
// Not this
const ModalComponent = Modal as React.ForwardRefExoticComponent<ModalProps & RefAttributes < HTMLDivElement >> & ModalStaticProps
ModalComponent.show = () => { };
ModalComponent.hide = () => { };
function Consumer() {
return <div onClick={() => ModalComponent.show()} />
}
解决方案
这是可行的。请参阅函数的属性声明。以自然的方式可以做到这一点,但它可能会破坏您的 ref 类型。
因此,我决定只使用Object.assign
参见示例:
import React, { ReactNode, RefAttributes, ForwardRefExoticComponent } from 'react';
interface ModalProps {
title: ReactNode;
}
interface ModalStaticProps {
show(): void;
hide(): void;
}
const STATIC_PROPS: ModalStaticProps = {
show: () => { },
hide: () => { }
}
const withStaticProps = <T,>(
forwarded: ForwardRefExoticComponent<ModalProps & RefAttributes<HTMLDivElement>>,
staticProps: T
) => Object.assign(forwarded, staticProps)
const Modal = React.forwardRef<
HTMLDivElement,
ModalProps
>(({ title }: ModalProps, ref) => <div ref={ref}>{title}</div>)
const ModalComponent = withStaticProps(Modal, STATIC_PROPS)
function Consumer() {
return <div onClick={() => ModalComponent.show()} />
}
请参阅我关于此问题的问题
推荐阅读
- python - 是否可以在仍在生成数据时计算中位数?Python 在线中位数计算器
- python - 无法安装 open3d 库(错误:找不到满足 open3d 要求的版本)
- .net-core - .Net Core 3.1 是否具有 InheritedExportAttribute?
- javascript - 使用名称获取输入的 id
- c++ - C/C++ DirectX9 将矩形中的像素复制到屏幕上的另一个矩形
- java - 晚上好,为什么我的代码没有在控制台中打印任何内容,尽管他有一个“system.out.println”指令?
- ios - Websockets 在 iOS 和 Safari 上不起作用 - OSSStatus 错误 9837
- python - 获取具有行单元条件的最大值列
- python - 带有交互图的循环函数
- javascript - 降低画布内动画粒子的 CPU 消耗