gpt4 book ai didi

javascript - 如何使用 useStyle 为 Material Ui 中的类组件设置样式

转载 作者:塔克拉玛干 更新时间:2023-11-02 22:38:57 27 4
gpt4 key购买 nike

我想使用 useStyle 来设置类组件的样式。但这可以很容易地完成钩子(Hook)。但我想改用组件。但我不知道该怎么做。

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;

最佳答案

你可以这样做:

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);

如果您没有使用主题,请忽略 withTheme: true


要使它在 TypeScript 中正常工作,需要进行一些更改:

import { createStyles, withStyles, WithStyles } from "@material-ui/core/styles";

const styles = theme => createStyles({
root: {
backgroundColor: "red"
}
});

interface Props extends WithStyles<typeof styles>{ }

class ClassComponent extends Component<Props> {

// the rest of the code stays the same

关于javascript - 如何使用 useStyle 为 Material Ui 中的类组件设置样式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56554586/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com