简体   繁体   English

具有高阶组件的通用组件

[英]Generic components with higher order components

I'd like to give my React component props a generic type but this is being lost when I wrap it in a higher order component (material-ui) how do I pass along the required information?我想给我的 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 gives an error as it doesn't know about the generic.使用<StyledComponent<myType会产生错误,因为它不知道泛型。

My bet is to annotate your new component like this:我打赌是这样注释你的新组件:

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

Mind you probably need to differentiate OuterProps and InnerProps , see below example I made for reference:请注意,您可能需要区分OuterPropsInnerProps ,请参见我制作的以下示例以供参考:

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

Hope that helps!希望有帮助!

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM