reactjs - 如何为 React 的“withProps”函数正确定义类型?
问题描述
这是我所拥有的:
export function withProps<P,U extends Partial<P>>(component: React.ComponentType<P>, defaultProps: U): React.FunctionComponent<P & U> {
return props => React.createElement(component, {...defaultProps, ...props});
}
这是我的使用尝试:
a
不应该是必需的Comp2
。
我尝试将定义更新为
React.FunctionComponent<Omit<P,keyof U>>
但它也不喜欢这样:
我认为正确的输出道具是Omit<P,keyof U> & U
. 即,我们删除所有默认道具,然后将它们作为部分(全部可选)添加回来,但我不知道如何让它工作。
解决方案
这有点棘手。为了实现提供的属性的分离,组合类型的声明需要像这样更改:TProps & TDefaultProps
. 这种组合类型还需要由 的主要参数Omit
。在类型 TProps
和TDefaultProps
分离之后,它们将没有任何共同的属性。因此,不可能将两个值都分配defaultProps
给props
同一个对象。因此,至少as any
需要一个。
function withProps<TProps, TDefaultProps>
(component: React.ComponentType<TProps & TDefaultProps>, defaultProps: TDefaultProps):
React.FC<Omit<TProps & TDefaultProps, keyof TDefaultProps>> {
return props => React.createElement(component, { ...defaultProps as any, ...props});
}
推荐阅读
- javascript - 将课程添加到活动幻灯片
- c# - 使用 OCR 精确复制文本
- r - 无法运行语句:查询期间丢失与 MySQL 服务器的连接
- python - 从扭曲的图像中检索像素的原始坐标
- ios - 没有这样的文件或目录:'SwiftyJSON'
- caching - 如何刷新 AMP 缓存?
- angular - Angular 5.2 中的 Angularfire2 编译问题
- apache - htaccess 使用 https 重定向到 index.php?idApp
- python-3.x - (mac) 我可以在我的电脑上没有安装浏览器的情况下在 Selenium 中运行 Microsoft Edge 吗?
- javascript - 为什么这个 JavaScript 在 Zapier 中循环了两次?