首页 > 解决方案 > 具有高阶组件的通用组件

问题描述

我想给我的 React 组件 props 一个泛型类型,但是当我将它包装在更高阶的组件(material-ui)中时,它会丢失我如何传递所需的信息?

type Props<T> = {
  data: Array<T>;
}

class MyComponent<T> extends React.Component<Props<T>> {

const StyledComponent = withStyles(styles)(MyComponent)

Using<StyledComponent<myType给出一个错误,因为它不知道泛型。

标签: reactjstypescriptmaterial-ui

解决方案


我敢打赌,像这样注释您的新组件:

const StyledComponent: <T>(props: OuterProps<T>) => JSX.Element = withStyles(styles)(MyComponent) ;

请注意,您可能需要区分OuterPropsInnerProps,请参阅以下示例以供参考:

https://stackblitz.com/edit/hoc-generics

希望有帮助!


推荐阅读