问题
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.jsSyntaxError: 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.jsimport 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:
- You need to include the
default
keyword in your exports. - In order to access the classes that withStyles creates you need to access them through props by using
props.classes.button
- 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 astheme.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.jsimport 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