是否有适用于类Components的React Material-UI makeStyles()函数的非摘机替代品 [英] Is there a non-hook alternative for the React Material-UI makeStyles() function that works for class Components
问题描述
我在Material-UI的react库中使用了makeStyles()函数,并收到以下错误消息
Im using the makeStyles() function in material-UI's react library, and am getting the following error
只能在函数组件的主体内部调用挂钩.
以下是我正在使用的代码类型的示例.
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>
)
}
}
我知道抛出错误是因为我试图在我的类组件中使用makeStyles()(如上所示).
I know the error is being thrown because I'm trying to use makeStyles() in my class component (As shown above).
但是,我很好奇Material-UI的react库中是否为类组件提供了makeStyles()的替代方法,或者在类组件中获得make-styles功能的语法是什么.
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.
推荐答案
makeStyles
只是一个高阶函数
(返回一个钩子),用于在功能组件中应用样式.您可以始终使用 withStyles
,它是 HOC
,具有完全相同的用途,并且可以同时为两个功能组件分类
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 styles = {
root: {
background: 'linear-gradient(45deg, #FE6B8B 30%, #FF8E53 90%)'
}
};
class Component extends React.Component{
render(){
const { classes } = this.props
return <div className={classes.foo} />
}
}
export default withStyles(styles)(Component)
这篇关于是否有适用于类Components的React Material-UI makeStyles()函数的非摘机替代品的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!