material-ui /如何使用' withStyles()'来设置HOC的样式?

时间:2018-06-11 10:29:26

标签: material-ui jss

我的HOC:

const withPaper = Component => props => (
  <Paper>
    <Component {...props} />
  </Paper>
);

export default withPaper;

我想要造型&#39; Paper&#39;使用withStyles()的组件:

const styles = theme => ({
  root: {
    backgroundColor: 'green'
  }
});

const withPaper = ?? => ?? => (
  <Paper className={classes.root}>
    <Component {...props} />
  </Paper>
);

export default withStyles(styles)(withPaper);

我怎样才能注入这个案例? 我的简单想法&#39; Component =&gt; ({classes,... props})=&gt;&#39;记录错误。

TypeError: Cannot call a class as a function

2 个答案:

答案 0 :(得分:4)

回答我自己的问题。

我忽略了HOC的回报。它返回'Component'而不是'React Element'。 我不确定,但我认为这是我不能从HOC之外注入课程的原因。

我的解决方案效果很好 - 在HOC内部造型:

const withPaper = Component => {
  const WithPaper = ({ classes, ...props }) => (
    <Paper className={classes.root}>
      <Component {...props} />
    </Paper>
  );

  const styles = theme => ({
    root: {
      backgroundColor: 'green'
    }
  });

  return withStyles(styles)(WithPaper);
};

export default withPaper;

仅供参考,TypeScript用户可以参考Rahel的答案。

答案 1 :(得分:3)

我自己正在学习Material-UI和TypeScript,我实际上正在努力解决同样的问题:-)如果您正在寻找JS解决方案,请道歉,但明确的类型可能实际上有帮助: / p>

import * as React from "react";
import createStyles from "@material-ui/core/styles/createStyles";
import { WithStyles } from "@material-ui/core";
import Paper from "@material-ui/core/Paper/Paper";
import { compose } from "recompose";
import withStyles from "@material-ui/core/styles/withStyles";

const styles = createStyles({
  root: {
    backgroundColor: "green"
  }
});

type WrapperProps = WithStyles<typeof styles>;

const withPaper = <P extends {}>(Component: React.ComponentType<P>) => {
  type Props = P & WrapperProps;

  return (props: Props) => {
    return (
      <Paper className={props.classes.root}>
        <Component {...props} />
      </Paper>
    );
  };
};

export default compose(withStyles(styles), withPaper);

Edit xvkwo6vzxz

请注意recomposecompose高阶组件的使用情况。如果你介意这个库依赖,你也可以不用:

export default (component: React.ComponentType) => withStyles(styles)(withPaper(component));