Jam*_*ith 3 javascript reactjs material-ui react-component react-hooks
我想使用useStyle设置类Component的样式。但这很容易实现。但我想改用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;
Run Code Online (Sandbox Code Playgroud)
ess*_*oub 24
对于类组件,您可以使用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)
Run Code Online (Sandbox Code Playgroud)
您可以这样做:
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);
Run Code Online (Sandbox Code Playgroud)
withTheme: true
如果您不使用主题,请忽略
小智 7
嘿我有一个类似的问题。我通过替换makeStyles
为解决了它withStyles
,然后在执行类似操作的地方const classes = useStyle();
将其替换为const classes = useStyle;
您注意到useStyle
不应是函数调用,而是变量赋值。
在您进行这些更改后,这应该可以正常工作。
useStyles
是一个反应钩子。您只能在功能组件中使用它。
这一行创建了钩子:
const useStyles = makeStyles(theme => ({ /* ... */ });
Run Code Online (Sandbox Code Playgroud)
您在函数组件中使用它来创建类对象:
const classes = useStyles();
Run Code Online (Sandbox Code Playgroud)
然后在 jsx 中使用类:
<div className={classes.paper}>
Run Code Online (Sandbox Code Playgroud)
推荐资源:https : //material-ui.com/styles/basics/ https://reactjs.org/docs/hooks-intro.html
归档时间: |
|
查看次数: |
4020 次 |
最近记录: |