Is there a non-hook alternative for the React Material-UI makeStyles() function that works for class Components

旧时模样 提交于 2020-02-04 05:21:11

问题


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

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