material-ui的官方示例css都是用makeStyles
创建的,用在function
组件上。
但是如果我用的是class
组件该怎么用呢?答案是用不了。
makeStyles
只能用在function
组件上,要在class
组件上使用需要用withStyles
。
用法如下:
import React, { Component } from 'react';
import { withStyles } from '@material-ui/core/styles';
import Button from '@material-ui/core/Button';
const styles = {
root: {
background: 'linear-gradient(45deg, #FE6B8B 30%, #FF8E53 90%)',
border: 0,
borderRadius: 3,
boxShadow: '0 3px 5px 2px rgba(255, 105, 135, .3)',
color: 'white',
height: 48,
padding: '0 30px'
}
};
class HigherOrderComponent extends Component {
render() {
const { classes } = this.props;
console.log('classes: ', classes);
return (
<>
<Button className={classes.root}>Higher-order component</Button>
</>
);
}
}
export default withStyles(styles)(HigherOrderComponent);
使用theme
:
import React from 'react';
import { withStyles } from '@material-ui/core/styles';
import Avatar from '@material-ui/core/Avatar';
import SupervisorAccountIcon from '@material-ui/icons/SupervisorAccount';
import Paper from '@material-ui/core/Paper';
import Grid from '@material-ui/core/Grid';
const useStyles = theme => ({
root: {
flexGrow: 1,
},
paper: {
padding: theme.spacing(2),
margin: 'auto',
maxWidth: 500,
marginTop: theme.spacing(8),
display: 'flex',
flexDirection: 'column',
alignItems: 'center',
},
image: {
width: 128,
height: 128,
},
img: {
margin: 'auto',
display: 'block',
maxWidth: '100%',
maxHeight: '100%',
},
});
class SignIn extends React.Component {
render () {
const { classes } = this.props;
return (
<Paper className={classes.paper}>
<Grid container direction="row" justify="center" alignItems="center">
<Avatar className="asdes">
<SupervisorAccountIcon color="action" />
</Avatar>
</Grid>
</Paper>
);
}
}
export default withStyles(useStyles)(SignIn);
本文链接:https://360us.net/article/68.html