小编Luk*_*ech的帖子

带有 withStyles 的 JSX 元素中的通用类型参数

在 React with material-ui 中,我试图创建一个 JSX 组件,它接受通用参数并使用withStylesHOC 来注入我的样式。

第一种方法是这样的:

const styles = (theme: Theme) => createStyles({
  card:    {
    ...
  }
});

interface Props<T> {
  prop: keyof T,
  ...
}

type PropsWithStyles<T> = Props<T> & WithStyles<typeof styles>;

export default withStyles(styles)(
    class BaseFormCard<T> extends React.Component<PropsWithStyles<T>> {
      ...
    }
),
Run Code Online (Sandbox Code Playgroud)

但是当尝试使用它时,泛型类型丢失了

<BaseFormCard<MyClass> prop={ /* no typings here */ } />
Run Code Online (Sandbox Code Playgroud)

我能找到的唯一解决方案是将导出包装在一个函数中,该函数采用泛型参数并构造组件。

export default function WrappedBaseFormCard<T>(props: Props<T>): ReactElement<Props<T>> {

  const wrapper = withStyles(styles)(
        class BaseFormCard<T> extends React.Component<PropsWithStyles<T>> {
          ...
        }
    ) as …
Run Code Online (Sandbox Code Playgroud)

typescript reactjs material-ui

5
推荐指数
1
解决办法
1883
查看次数

标签 统计

material-ui ×1

reactjs ×1

typescript ×1