javascript - Material UI v4: Jag vill anpassa en Material UI-knapp inom en klasskomponent med TypeScript. Vänligen låt mig veta hur jag kan göra det?


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

ovanstående kod från https://mui.com/styles/basics/#higher-order-component-api kan jag inte konvertera till en klasskomponent

Svar #1

Du kan använda makeStyles för detta.

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

Se även dokumentationen om makeStyles för mer information: https://mui.com/styles/advanced/#overriding-styles-classes-prop


Redigera: Om du vill använda en klasskomponent kan du använda createStyles i kombination med withStyles.

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