How to export a stateless functional component with styles in Reactjs

家住魔仙堡 提交于 2019-12-11 13:48:04

问题


I have a file named MyButtons.js from which I want to export two stateless functional components one of which contains a style variable. But I get the following error.

path/to/MyButtons.js

SyntaxError: path/to/MyButtons.js: Support for the experimental syntax 'exportDefaultFrom' isn't currently enabled (64:8):

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

What am I doing wrong?

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

回答1:


You forgot the default keyword :

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



回答2:


  1. You need to include the default keyword in your exports.
  2. In order to access the classes that withStyles creates you need to access them through props by using props.classes.button
  3. You also need to make sure that withStyles passes the theme property into your styles function. By default this is set to false. Without this you will not be able to access properties such as theme.spacing.unit.

In summary you need to change your final line to the following:

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



回答3:


In addition to the accepted answer, you also need to add classes to the input props object as follows.

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

So the entire file reads as follows. (Edit: Incorporated answer by @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 })


来源:https://stackoverflow.com/questions/54752924/how-to-export-a-stateless-functional-component-with-styles-in-reactjs

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!