首页 > 解决方案 > 如何为 ForwardRefExoticComponent 添加静态道具类型

问题描述

我有一个FC ,Modal我需要向它添加两个静态方法。我不知道如何为组件添加类型。这样我就可以在不使用类型断言的情况下直接分配和分配给。showhideModalStaticPropsshowhideModal

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()} />
}

打字稿游乐场

标签: reactjstypescript

解决方案


这是可行的。请参阅函数的属性声明。以自然的方式可以做到这一点,但它可能会破坏您的 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()} />
}

操场

请参阅我关于此问题的问题


推荐阅读