React和Typescript组件对`Component`的道具类型

麦克

我在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

提香·切尔尼科娃·德拉戈米尔

如果要保留类型安全性,则需要将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给组件时,我们确实需要使用类型断言,因为typescript不能找出{ Component: C, showIfTrue: boolean} & React.ComponentProps<C>负号ComponentshowIfTrue而只是React.ComponentProps<C>但您不能拥有全部:)

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章

React 组件的精确 TypeScript 道具类型

TypeScript和React中的联合类型道具

React + Typescript:无状态/无道具的React组件的类型

具有多种道具类型的 Typescript React 功能组件

将TypeScript类型作为道具传递给React组件?

React 道具和组件

React和Typescript:如何扩展通用组件道具?

如何通用键入React组件道具和扩展通用道具类型

TypeScript React Functional Component-类型'Element'缺少以下属性:类型,道具,键错误

TypeScript 没有强制执行通用的交集类型(React 组件道具)

使用Composition API和Typescript输入系统对Vue组件进行强类型输入的道具

根据道具更改react组件的类型

在TypeScript的React组件中实现“作为”道具

Typescript&React:在组件之间传递道具与默认道具

通过Typescript和React在私有路由中传递组件道具

是否建议将 TypeScript 接口用于声明文件和 React 组件道具?

将无类型字符串传递给带有类型道具的 React 组件时出现 TypeScript 错误?

TypeScript React SFC子道具类型错误

Reactjs,Typescript-在Typescript中投放道具-React组件

TypeScript条件类型:从react组件中提取组件props类型

如何用类型和基本的React函数组件的Jest和Typescript进行测试

如何使用defaultProps从React组件中提取道具类型?

React 组件的自定义类型 - 道具不匹配

React组件为作为道具传入的函数抛出TypeScript错误

将道具传递给Typescript中的React样式的组件

TypeScript React,无法将道具发送到组件

将功能作为道具传递给Typescript React功能组件

如何从 React 的包装器中获取组件中的道具?(+TypeScript)

React + TypeScript:将数组中的组件作为道具传递