大佬教程收集整理的这篇文章主要介绍了Writing a React higher-order component with TypeScript,大佬教程大佬觉得挺不错的,现在分享给大家,也给大家做个参考。
我找到了一种使其工作的方法:通过使用hoc
提供的type
参数调用
,如下所示:
import ChildComponent, { Props as ChildComponentProps } from './child';
const WrappedChildComponent = hoc<ChildComponentProps>()(ChildComponent);
但我不是很喜欢。它要求我导出孩子的道具 (我宁愿不这样做),我 有种感觉,我正在告诉TypeScript 它应该能够推断出的东西。
我正在 用TypeScript 写一个React高阶组件(HOC)。HOC应该比包装的
组件接受更多的道具,所以我这样写:
type HocProps {
// Contains the prop my HOC needs
thingy: number
}
type Component<P> = React.ComponentClass<P> | React.StatelessComponent<P>
interface ComponentDecorator<TChildProps> {
(component: Component<TChildProps>): Component<HocProps & TChildProps>;
}
const hoc = function<TChildProps>(): (component: Component<TChildProps>) => Component<HocProps & TChildProps) {
return (Child: Component<TChildProps>) => {
class MyHOC extends React.Component<HocProps & TChildProps,void> {
// Implementation skipped for brevity
}
return MyHOc;
}
}
export default hoc;
换句话说,hoc
是产生实际HOC的函数。(我相信)此HOC
是接受a的函数Componen
t。由于我事先不知道被包装的组件是什么,因此我使用泛型类型TChildProps
来定义被包装的组件的道具形状。该函数还
返回Component
。返回的组件接受包装组件的道具(再次,使用generic
键入TChildProps
),并
为其自身需要一些道具(类型HocProps
)。使用返回的组件时,应提供所有道具(包括HocProps
包装好的道具Component
)。
现在,当我尝试使用HOC时,请执行以下操作:
// outside parent component
const WrappedChildComponent = hoc()(ChildComponent);
// inside parent component
render() {
return <WrappedChild
thingy={ 42 }
// Prop `foo` required by ChildComponent
foo={ 'bar' } />
}
But I get a TypeScript error:
TS2339: Property 'foo' does not exist on type 'IntrinsicAttributes & HocProps & {} & { children? ReactNode; }'
在我看来TypeScript并没有替换TChildProps
为所需的道具的形状ChildComponent
。如何使TypeScript
做到这一点?
以上是大佬教程为你收集整理的Writing a React higher-order component with TypeScript全部内容,希望文章能够帮你解决Writing a React higher-order component with TypeScript所遇到的程序开发问题。
如果觉得大佬教程网站内容还不错,欢迎将大佬教程推荐给程序员好友。
本图文内容来源于网友网络收集整理提供,作为学习参考使用,版权属于原作者。
如您有任何意见或建议可联系处理。小编QQ:384754419,请注明来意。