【问题标题】:material-ui / How to style an HOC using 'withStyles()'?material-ui / 如何使用 'withStyles()' 设置 HOC 样式?
【发布时间】:2018-11-20 13:57:28
【问题描述】:

我的 HOC:

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

export default withPaper;

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

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

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

export default withStyles(styles)(withPaper);

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

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

【问题讨论】:

    标签: material-ui jss


    【解决方案1】:

    回答我自己的问题。

    我忽略了 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 的答案。

    【讨论】:

      【解决方案2】:

      我自己正在学习 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);
      

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

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

      【讨论】:

      • 虽然我对TS不熟悉,但是这对使用TS的人来说还是很有帮助的。谢谢,拉赫尔。
      猜你喜欢
      • 2019-09-21
      • 2021-01-06
      • 2019-11-21
      • 2020-11-16
      • 2021-04-11
      • 2019-06-14
      • 2022-08-10
      • 2021-02-05
      • 1970-01-01
      相关资源
      最近更新 更多