问题
Im using the makeStyles() function in material-UI's react library, and am getting the following error
Hooks can only be called inside the body of a function component.
Below is an example of the kind of code I am using.
const useStyles = makeStyles(theme => ({
container: {
display: 'flex',
flexWrap: 'wrap',
},
textField: {
marginLeft: theme.spacing(1),
marginRight: theme.spacing(1),
},
dense: {
marginTop: theme.spacing(2),
},
menu: {
width: 200,
},
}));
class Demo extends Component {
constructor(props) {
super(props);
}
render() {
const classes = useStyles();
return (
<TextField
className={classes.textField}
>
<MenuItem>Demo</MenuItem>
</TextField>
)
}
}
I know the error is being thrown because I'm trying to use makeStyles() in my class component (As shown above).
However, I'm curious if there is an alternative to makeStyles() for class components in Material-UI's react library, or what the syntax would be to get the functionality of make-styles in a class component.
回答1:
makeStyles
is just a high order function
(returns a hook) to apply styles in functional components. You can always use withStyles
, which is an HOC
for the exact same purpose and works for both class an functional components
import { withStyles } from '@material-ui/styles'
const Component = withStyles(styles)(({classes}) =>{
return <div className={classes.foo} /<
})
class Component extends React.Component{
render(){
const { classes } = this.props
return <div className={classes.foo} />
}
}
export default withStyles(styles)(Component)
来源:https://stackoverflow.com/questions/58441802/is-there-a-non-hook-alternative-for-the-react-material-ui-makestyles-function