在 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)