首页 > 解决方案 > 状态组件的 React Native 高阶组件

问题描述

我正在尝试使用 Typescript 为 React Native 中的状态组件做一个 hoc,我想将它用作装饰器。我的类型定义如下:

export function hoc<T extends ComponentClass>(target: any): T {
  return (target: any) =>
    class MyClass extends Component<any, any> {

    }
}

但我得到了错误Type '(target: any) => typeof MyClass' is not assignable to type 'T'

我应该改变什么以使其正确使用打字稿?

标签: reactjstypescriptreact-nativehigh-order-component

解决方案


您可以使用此类型来表示每个返回的实例都与调用它的类型相同:

class MyClass {

    public each<T extends MyClass>(callback: (item: T) => void): this {
        /* Loop through an array and apply the callback */
        return this;
    }

}

class Derived extends MyClass {
    foo: string;
}

let derived = new Derived;

derived = derived.each(() => {});

这可能会帮助你


推荐阅读