【问题标题】:Higher order class with generics in Javascript?Javascript中具有泛型的高阶类?
【发布时间】:2018-01-31 02:53:32
【问题描述】:

我想知道是否有适当的方法来包装类似于 React Native 中的高阶组件的类?我有以下内容:

const RecyclerViewDataWrap = <P>(Wrapee: Class<React$Component<P, *>>) => {
  return class {
    props: P

    constructor(props: P){
      this.props = props
    }
    render(){
      return (
        <Wrapee {... this.props}  />
      )
    }
  }
}

export default RecyclerViewDataWrap

// in some other component file:
export const SomeComponentData = RecyclerViewDataWrap(SomeComponent)

这允许我创建 SomeComponentData 对象,这些对象将使用我告诉它的道具呈现 SomeComponents。但是,我希望能够连同它一起声明泛型类型,以便构造函数可以知道它想要什么类型。理想情况下,我想做这样的事情:

type Props = {
  title?: string,
  price?: number,
}
export const SomeComponentData = RecyclerViewDataWrap<Props>(SomeComponent)

【问题讨论】:

标签: javascript typescript react-native generics flowtype


【解决方案1】:

我已经知道了(我使用类 Props 而不是类型):

说你有

class SomeComponent {
    constructor(public name: string) {
    }
}

class Props {
    title?: string;
    price?: number;
}

那么你可以这样做:

type Constructor<T> = new(...args: any[]) => T;

function RecyclerViewDataWrap<P, T extends Constructor<{}>>(Props: new ()=> P, Base: T) {

    return class extends Base {
        props: P = new Props();

        constructor(...args: any[]) {
            super(...args);
        }
    }
}

const SomeComponentData = RecyclerViewDataWrap(Props, SomeComponent);


let componentData = new SomeComponentData("My Component");
componentData.props.title = 'My title';

console.log(componentData);

我主要基于https://github.com/Microsoft/TypeScript/wiki/What%27s-new-in-TypeScript#support-for-mix-in-classesTypescript instantiate generic object

也许@cartant 可以验证这一点,因为他似乎知道更多这些东西。

【讨论】:

  • @cartant 可以验证一下吗?
猜你喜欢
  • 2020-03-11
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-10-24
  • 1970-01-01
  • 2020-08-30
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多