【问题标题】:How to export a stateless functional component with styles in Reactjs如何在 Reactjs 中导出具有样式的无状态功能组件
【发布时间】:2019-07-12 04:05:20
【问题描述】:

我有一个名为 MyButtons.js 的文件,我想从中导出两个无状态功能组件,其中一个包含一个 style 变量。但我收到以下错误。

路径/到/MyButtons.js

SyntaxError: path/to/MyButtons.js: 对实验性语法“exportDefaultFrom”的支持当前未启用 (64:8):

64 |导出 withStyles(styles)({ AllButtonsRow, UDButtons, });

我做错了什么?

MyButtons.js
import React from 'react';
import { withStyles, } from '@material-ui/core';

const styles = theme => ({
  button: {
    margin: theme.spacing.unit,
  },
});

const MyRegularButton = props => (<Button>Click me!</Button>);

const MyStyledButton = props => (<Button className={classes.button}>Click me!</Button>);

export withStyles(styles)({ MyRegularButton, MyStyledButton, });

【问题讨论】:

    标签: css reactjs jss


    【解决方案1】:

    您忘记了 default 关键字:

    export default withStyles(styles)({ MyRegularButton, MyStyledButton })
    

    【讨论】:

      【解决方案2】:
      1. 您需要在导出中包含 default 关键字。
      2. 为了访问 withStyles 创建的类,您需要使用 props.classes.button 通过 props 访问它们
      3. 您还需要确保 withStyles 将theme 属性传递到您的样式函数中。 By default this is set to false。没有这个,您将无法访问诸如theme.spacing.unit 之类的属性。

      总而言之,您需要将最后一行更改为以下内容:

      export default withStyles(styles, { withTheme: true })({ MyRegularButton, MyStyledButton })
      

      【讨论】:

        【解决方案3】:

        除了接受的答案外,您还需要将classes 添加到输入props 对象中,如下所示。

        const MyStyledButton = ({ classes, }) => (...
        

        所以整个文件的内容如下。 (编辑:@MattC 的合并答案)

        MyButtons.js
        import React from 'react';
        import { withStyles, } from '@material-ui/core';
        
        const styles = theme => ({
          button: {
            margin: theme.spacing.unit,
          },
        });
        
        const MyRegularButton = props => (<Button>Click me!</Button>);
        
        const MyStyledButton = ({ classes, }) => (
          <Button className={classes.button}>Click me!</Button>
        );
        
        export default withStyles(styles, { withTheme: true })({ MyRegularButton, MyStyledButton })
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2019-03-10
          • 2021-07-21
          • 1970-01-01
          • 1970-01-01
          • 2020-08-19
          • 1970-01-01
          • 1970-01-01
          • 2018-09-29
          相关资源
          最近更新 更多