7

我的 HOC:

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

export default withPaper;

我想使用以下方式设置“Paper”组件的样式withStyles()

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

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

export default withStyles(styles)(withPaper);

在这种情况下,我如何注入类道具?我的简单想法Component => ({classes, ...props}) =>记录错误。

TypeError:无法将类作为函数调用

4

2 回答 2

6

回答我自己的问题。

我忽略了 HOC 的回报。它返回“组件”而不是“反应元素”。我不确定,但我认为这就是我无法从 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 的答案。

于 2018-06-18T03:14:47.803 回答
4

我自己也在学习 Material-UI 和 TypeScript,实际上我也在为同样的事情苦苦挣扎:-) 如果您正在寻找 JS 解决方案,我很抱歉,但是明确的类型实际上可能会有所帮助:

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

编辑 xvkwo6vzxz

请注意recomposecompose您的高阶组件的使用。如果您介意这种库依赖关系,您也可以不这样做:

export default (component: React.ComponentType) => withStyles(styles)(withPaper(component));
于 2018-06-15T09:55:41.103 回答