javascript 如何在 Material Ui 中使用 useStyle 为类组件设置样式
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/56554586/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to use useStyle to style Class Component in Material Ui
提问by Jamith
I want to use useStyle to style the Class Component . But this can be easily done hooks. but i want to use Component instead. But I cant figure out how to do this.
我想使用 useStyle 来设置 Class Component 的样式。但这可以很容易地完成钩子。但我想改用组件。但我无法弄清楚如何做到这一点。
import React,{Component} from 'react';
import Avatar from '@material-ui/core/Avatar';
import { makeStyles } from '@material-ui/core/styles';
import LockOutlinedIcon from '@material-ui/icons/LockOutlined';
const useStyles = makeStyles(theme => ({
'@global': {
body: {
backgroundColor: theme.palette.common.white,
},
},
paper: {
marginTop: theme.spacing(8),
display: 'flex',
flexDirection: 'column',
alignItems: 'center',
},
avatar: {
margin: theme.spacing(1),
backgroundColor: theme.palette.secondary.main,
}
}));
class SignIn extends Component{
const classes = useStyle(); // how to assign UseStyle
render(){
return(
<div className={classes.paper}>
<Avatar className={classes.avatar}>
<LockOutlinedIcon />
</Avatar>
</div>
}
}
export default SignIn;
回答by Vicente
You can do it like this:
你可以这样做:
import { withStyles } from "@material-ui/core/styles";
const styles = theme => ({
root: {
backgroundColor: "red"
}
});
class ClassComponent extends Component {
state = {
searchNodes: ""
};
render() {
const { classes } = this.props;
return (
<div className={classes.root}>Hello!</div>
);
}
}
export default withStyles(styles, { withTheme: true })(ClassComponent);
Just ignore the withTheme: trueif you aren't using a theme
withTheme: true如果您不使用主题,请忽略
回答by essayoub
for class Components you can use withStylesinstead of makeStyles
对于类组件,您可以使用withStyles而不是makeStyles
import { withStyles } from '@material-ui/core/styles';
const useStyles = theme => ({
fab: {
position: 'fixed',
bottom: theme.spacing(2),
right: theme.spacing(2),
},
});
class ClassComponent extends Component {
render() {
const { classes } = this.props;
{/** your UI components... */}
}
}
export default withStyles(useStyles)(ClassComponent)
回答by Kania
useStylesis a react hook. You can use it in function component only.
useStyles是一个反应钩子。您只能在功能组件中使用它。
This line creates the hook:
这一行创建了钩子:
const useStyles = makeStyles(theme => ({ /* ... */ });
You are using it inside the function component to create classes object:
您在函数组件中使用它来创建类对象:
const classes = useStyles();
Then in jsx you use classes:
然后在 jsx 中使用类:
<div className={classes.paper}>
Suggested resources: https://material-ui.com/styles/basics/https://reactjs.org/docs/hooks-intro.html
推荐资源:https: //material-ui.com/styles/basics/ https://reactjs.org/docs/hooks-intro.html

