首页 > 解决方案 > `Component` 的 React 和 Typescript 组件道具类型

问题描述

我在 React 中有以下 HOC:

`restricted` prop
    const ConditionalSwitch = ({component: Component, showIfTrue, ...rest}) => (

    showIfTrue
        ? <Component {...rest}/>
        : null
);

如何定义道具以便 Typescript 满意?

{component: Component, showIfTrue, ...rest}

我试过了

export interface CSProps {
    component: any,
    showIfTrue: boolean
}

我该如何处理...rest这里?

标签: reactjstypescript

解决方案


如果要保持类型安全,则需要进行ConditionalSwitch泛型并让它根据Component. 这将确保客户端ConditionalSwitch将传递所用组件的所有必需属性。为此,我们使用此处描述的方法:

const ConditionalSwitch = <C extends React.ComponentType<any>>({ Component,  showIfTrue, ...rest}: { Component: C, showIfTrue: boolean} & React.ComponentProps<C> ) => (
    showIfTrue
        ? <Component {...(rest as any) }/>
        : null
);

function TestComp({ title, text}: {title: string, text: string}) {
    return null!;
}

let e = <ConditionalSwitch Component={TestComp} showIfTrue={true} title="aa" text="aa" />  // title and text are checked

将 传递rest给组件时,我们确实需要使用类型断言,因为打字稿无法找出{ Component: C, showIfTrue: boolean} & React.ComponentProps<C>减号Component并且showIfTrue只是React.ComponentProps<C>但你不能拥有它:)


推荐阅读