reactjs - `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
这里?
解决方案
如果要保持类型安全,则需要进行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>
但你不能拥有它:)
推荐阅读
- asp.net-core - 以编程方式生成请求验证令牌
- c# - .net core 3.1 clientFactory在请求正文中传递json字符串
- node.js - 在带角度的电子中使用 SQL Server 时出错:__webpack_require__(...) 不是函数
- asp.net - Bootstrap3 将 asp.net 文本框并排对齐到 asp.net RadioButtonList 特定列表项
- c# - net core 3.1 Bearer 401 未授权
- php - laravel 7 - 在现有表上添加新图像
- node.js - 能够连接到 redis 但设置/获取超时
- python - 如何在 django 模板中使用 pk 检查对象是否存在?
- javascript - 当所有特定元素都显示时触发的 JavaScript 事件:无
- css - Bootstrap 动态设置徽章的颜色