程序问答   发布时间:2022-06-02  发布网站:大佬教程  code.js-code.com
大佬教程收集整理的这篇文章主要介绍了Writing a React higher-order component with TypeScript大佬教程大佬觉得挺不错的,现在分享给大家,也给大家做个参考。

如何解决WriTing a React higher-order component with TypeScript?

开发过程中遇到WriTing a React higher-order component with TypeScript的问题如何解决?下面主要结合日常开发的经验,给出你关于WriTing a React higher-order component with TypeScript的解决方法建议,希望对你解决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的函数Component。由于我事先不知道被包装的组件是什么,因此我使用泛型类型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,请注明来意。