【问题标题】:Material ui v4: I want to customize a Material UI button inside a class component using types script. Kindly let me know how can I do it?Material ui v4:我想使用类型脚本在类组件中自定义一个 Material UI 按钮。请让我知道我该怎么做?
【发布时间】:2021-11-17 12:29:20
【问题描述】:
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',
  },
};
function HigherOrderComponent(props) {
  const { classes } = props;
  return <Button className={classes.root}>Higher-order component</Button>;
}

HigherOrderComponent.propTypes = {
  classes: PropTypes.object.isRequired,
};

export default withStyles(styles)(HigherOrderComponent);

以上来自https://mui.com/styles/basics/#higher-order-component-api的代码我无法转换成类组件

【问题讨论】:

    标签: javascript reactjs typescript material-ui


    【解决方案1】:

    您可以为此使用makeStyles

    const useStyles = makeStyles({
        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',
        },
    });
    
    export default function HigherOrderComponent() {
        const classes = useStyles();
        return <Button className={classes.root}>Higher-order component</Button>;
    }
    

    有关更多信息,另请参阅有关 makeStyles 的文档:https://mui.com/styles/advanced/#overriding-styles-classes-prop


    编辑:如果你想使用类组件,你可以使用createStyleswithStyles

    import { Button, createStyles, WithStyles, withStyles } from '@material-ui/core';
    import React, { PureComponent } from 'react';
    
    const styles = createStyles({
        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',
        },
    });
    
    type PropsType = WithStyles<typeof styles>;
    
    export class HigherOrderComponent extends PureComponent<PropsType> {
        constructor(props: PropsType) {
            super(props);
        }
    
        render() {
            return <Button className={this.props.classes.root}>Higher-order component</Button>;
        }
    }
    
    export default withStyles(styles)(HigherOrderComponent);
    

    【讨论】:

    • 我想为类组件复制相同的内容!尝试使用 with 样式但没有工作参考链接:stackoverflow.com/questions/68307446/….
    • 哦,对了,我以为你有一个类组件,现在正在使用函数式组件。我已经用类组件的示例更新了我的答案。
    猜你喜欢
    • 2017-03-03
    • 1970-01-01
    • 2011-06-21
    • 2020-12-03
    • 1970-01-01
    • 1970-01-01
    • 2020-09-15
    • 2020-04-16
    • 2022-06-22
    相关资源
    最近更新 更多