【问题标题】:React material-ui withStyles on external file not workingReact material-ui withStyles 对外部文件不起作用
【发布时间】:2019-06-13 09:35:53
【问题描述】:

我查看了this question,但仍然设法让它工作。

目的是将样式与组件文件分开,以便进行更清晰的设置。

当没有theme 参与时,它可以正常工作。

我确实尝试了几次迭代,无论是否将 withStyles 包裹在 style.js 文件。

下面的特定示例当然会抛出错误

TypeError: "theme.spacing is not a function"

所以我为css 创建了一个文件,如下所示

styles.js

 import { withStyles } from '@material-ui/core/styles';

export default theme => ({
...
 textField: {
    marginLeft: theme.spacing(1),
    marginRight: theme.spacing(1),
 }
 ...
});

然后在组件文件上:

login.js

import styles from './styles';
...
render() {
   const { classes } = this.props;
}
...
export default withCookies(withRouter(connect(mapStateToProps, mapDispatchToProps)(withStyles(styles, { withTheme: true })(Login))));

【问题讨论】:

    标签: javascript reactjs material-ui


    【解决方案1】:
    import { withStyles } from '@material-ui/core';
    
    import { Component } from './component';
    import { Styles } from './styles';
    
    
    export const StyledContainer = withStyles(
        CStyles,
    )(Component);
    

    在styles.ts中

    import { createStyles, Theme } from '@material-ui/core/styles';
    
    /**
     * Styles for Component
     */
    export const Styles = (theme: Theme) =>
        createStyles({
            '.className': {
                fontSize: 10,
            },
        });
    

    【讨论】:

      【解决方案2】:

      你用的是哪个material-ui版本?

      4.x版本中,theme.spacing是一个函数:

      export interface Spacing {
        (): number;
        (value1: SpacingArgument): number;
        (value1: SpacingArgument, value2: SpacingArgument): string;
        (value1: SpacingArgument, value2: SpacingArgument, value3: SpacingArgument): string;
        (
          value1: SpacingArgument,
          value2: SpacingArgument,
          value3: SpacingArgument,
          value4: SpacingArgument,
        ): string;
      }
      

      但在3.x 中,theme.spacing 是一个对象:

      export interface Spacing {
        unit: number;
      }
      

      【讨论】:

      • 使用 react material-ui v 4.0.1
      • 那么您能否记录或调试themetheme.spacing 的值?很奇怪,因为theme是函数参数,应该和styles函数定义的地方没有关系。
      猜你喜欢
      • 2018-04-11
      • 1970-01-01
      • 2016-12-26
      • 2019-10-06
      • 1970-01-01
      • 2022-01-09
      • 2019-06-14
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多