使用 TypeScript 编写 React 高阶组件

IT技术 reactjs typescript higher-order-components
2021-05-13 17:21:18

我正在使用 TypeScript编写React 高阶组件 (HOC)HOC 应该比被包裹的组件多接受一个 prop,所以我写了这个:

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(我相信)是一个接受Component. 由于我事先不知道包裹组件是什么,所以我使用泛型类型TChildProps来定义包裹组件的 props 的形状。该函数还返回一个Component. 返回的组件接受包装组件的 props(同样,使用 generic 类型TChildProps它自己需要的一些 props(type HocProps)。使用返回的组件时,应提供所有props(包括HocProps包装的propsComponent)。

现在,当我尝试使用我的 HOC 时,我会执行以下操作:

// outside parent component
const WrappedChildComponent = hoc()(ChildComponent);

// inside parent component
render() {
    return <WrappedChild
                thingy={ 42 } 
                // Prop `foo` required by ChildComponent
                foo={ 'bar' } />
}

但是我收到一个typescript错误:

TS2339: Property 'foo' does not exist on type 'IntrinsicAttributes & HocProps & {} & { children? ReactNode; }'

在我看来,typescript不更换TChildProps用的props所需要的形状ChildComponent我怎样才能让 TypeScript 做到这一点?

4个回答

聚会有点晚了。我喜欢使用 Omit TypeScript 实用程序类型来解决这个问题。文档链接:https : //www.typescriptlang.org/docs/handbook/utility-types.html#omitk

import React, {ComponentType} from 'react';

export interface AdditionalProps {
    additionalProp: string;
}

export function hoc<P extends AdditionalProps>(WrappedComponent: ComponentType<P>) : ComponentType<Omit<P, 'additionalProp'>> {
    const additionalProp = //...
    return props => (
        <WrappedComponent
            additionalProp={additionalProp}
            {...props as any}
        />
    );
}

如果您要求的是是否可以定义一个可以添加新props的 HOC,让我们对组件说“thingy”,而不修改该组件的 props 定义以包含“thingy”,我认为这是不可能的。

那是因为在代码中的某个时刻,您最终会得到:

render() {
    return (
        <WrappedComponent thingy={this.props.thingy} {...this.props}/>
    );
}

如果WrappedComponent不包含thingy在其 props 定义中,则总是会抛出错误孩子必须知道它收到了什么。顺便说一句,我想不出将props传递给无论如何都不知道它的组件的原因。您将无法在没有错误的情况下在子组件中引用该props。

我认为诀窍是将 HOC 定义为围绕孩子的props的泛型,然后只thingy在该孩子的界面中明确包含您的props或任何内容。

interface HocProps {
    // Contains the prop my HOC needs
    thingy: number;
}

const hoc = function<P extends HocProps>(
    WrappedComponent: new () => React.Component<P, any>
) {
    return class MyHOC extends React.Component<P, any> {
        render() {
            return (
                <WrappedComponent {...this.props}/>
            );
        }
    }
}
export default hoc;

// Example child class

// Need to make sure the Child class includes 'thingy' in its props definition or
// this will throw an error below where we assign `const Child = hoc(ChildClass)`
interface ChildClassProps {
    thingy: number;
}

class ChildClass extends React.Component<ChildClassProps, void> {
    render() {
        return (
            <h1>{this.props.thingy}</h1>
        );
    }
}

const Child = hoc(ChildClass);

当然,这个示例 HOC 并没有真正做任何事情真的 HOC 应该做某种逻辑来为 child props提供一个值。例如,也许您有一个组件可以显示一些重复更新的通用数据。您可以通过不同的方式更新它并创建 HOC 来分离该逻辑。

你有一个组件:

interface ChildComponentProps {
    lastUpdated: number;
    data: any;
}

class ChildComponent extends React.Component<ChildComponentProps, void> {
    render() {
        return (
            <div>
                <h1>{this.props.lastUpdated}</h1>
                <p>{JSON.stringify(this.props.data)}</p>
            </div>
        );
    }
}

然后一个仅使用固定间隔更新子组件的示例 HOCsetInterval可能是:

interface AutoUpdateProps {
    lastUpdated: number;
}

export function AutoUpdate<P extends AutoUpdateProps>(
    WrappedComponent: new () => React.Component<P, any>,
    updateInterval: number
) {
    return class extends React.Component<P, any> {
        autoUpdateIntervalId: number;
        lastUpdated: number;

        componentWillMount() {
            this.lastUpdated = 0;
            this.autoUpdateIntervalId = setInterval(() => {
                this.lastUpdated = performance.now();
                this.forceUpdate();
            }, updateInterval);
        }

        componentWillUnMount() {
            clearInterval(this.autoUpdateIntervalId);
        }

        render() {
            return (
                <WrappedComponent lastUpdated={this.lastUpdated} {...this.props}/>
            );
        }
    }
}

然后我们可以创建一个组件,每秒更新一次我们的孩子,如下所示:

const Child = AutoUpdate(ChildComponent, 1000);

我找到了一种使其工作的方法:通过使用hoc提供的类型参数调用,如下所示:

import ChildComponent, { Props as ChildComponentProps } from './child';
const WrappedChildComponent = hoc<ChildComponentProps>()(ChildComponent);

但我真的不喜欢它。它需要我导出孩子的props(我宁愿不这样做),而且我感觉我在告诉 TypeScript 一些它应该能够推断出的东西。

我发现以下关于 Pluralsight 的文章对理解 Typescript 中的 HOC 及其基本概念非常有帮助。我遇到的所有其他文章过去都是从这里和那里混合搭配的东西,这一步一步奏效,清晰简洁:

文章链接