我想知道是否有一种正确的方法来包装类似于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)
答案 0 :(得分: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-classes 和Typescript instantiate generic object
也许@cartant可以验证这一点,因为他似乎更了解这些东西。