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

Pet*_*ark 5 material-ui jss

我的HOC:

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

export default withPaper;
Run Code Online (Sandbox Code Playgroud)

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

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

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

export default withStyles(styles)(withPaper);
Run Code Online (Sandbox Code Playgroud)

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

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

Pet*_*ark 5

回答我自己的问题。

我忽略了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;
Run Code Online (Sandbox Code Playgroud)

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


Rah*_*thy 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);
Run Code Online (Sandbox Code Playgroud)

编辑

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

export default (component: React.ComponentType) => withStyles(styles)(withPaper(component));
Run Code Online (Sandbox Code Playgroud)