【发布时间】:2019-07-25 03:51:38
【问题描述】:
我正在尝试将现有的反应组件 (react-select) 包装在高阶组件 (HoC) 中,以提供一些条件渲染逻辑。我面临的困难是让 TypeScript 生成一个结合了 HoC 包装器和 Wrapped 组件属性的组件。
例如:
import React from "react";
import Select from "react-select";
interface HOCProps {
foo: string
}
// Return a type with the HOCProps properties removed.
type WitoutPrefilled<T extends HOCProps> = Pick<T, Exclude<keyof T, 'foo'>>;
function withHoC<P extends HOCProps>(WrappedComponent: React.ComponentType<P>) {
return class SomeHOC extends React.Component<WithoutPrefilled<P>> {
public render(): JSX.Element {
return <WrappedComponent {...this.props as P} /*foo={"test"}*/ />;
}
};
}
// Generate a wrapped component with a property union of the wrapped Select and outer HoC (HOCProps & Select) ?
const Wrapped = withHoC(Select);
实现此目的的正确方法是什么?
反应 16.8.3 打字稿 3.3.3
【问题讨论】:
-
问题出在哪里?您的解决方案看起来不错。
-
除非它导致这个编译器错误:
(TS) Argument of type 'typeof Select' is not assignable to parameter of type 'ComponentType<HOCProps>'. Type 'typeof Select' is not assignable to type 'ComponentClass<HOCProps, any>'. Types of property 'defaultProps' are incompatible. Type 'Props<any>' has no properties in common with type 'Partial<HOCProps>'.
标签: reactjs typescript high-order-component