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

时间:2019-06-12 04:14:50

标签: javascript reactjs material-ui react-hooks react-component

我想使用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;

6 个答案:

答案 0 :(得分:10)

您可以这样做:

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

答案 1 :(得分:6)

嘿,我有类似的问题。我用makeStyles替换了withStyles,然后在做类似const classes = useStyle();的地方,用const classes = useStyle;

替换了它。

您注意到useStyle不应该是函数调用,而应该是变量赋值。

进行这些更改后,该方法应该可以正常工作。

答案 2 :(得分:2)

useStyles是一个反应挂钩。您只能在功能组件中使用它。

此行创建钩子:

const useStyles = makeStyles(theme => ({ /* ... */ });

您正在函数组件内部使用它来创建类对象:

const classes = useStyles();

然后在jsx中使用类:

<div className={classes.paper}>

建议资源: https://material-ui.com/styles/basics/ https://reactjs.org/docs/hooks-intro.html

答案 3 :(得分:2)

就像已经说明的其他答案一样,您应该使用withStyles来扩充组件,并通过属性传递classes。我已经自由地将Material-UI stress test example修改为使用类组件的变体。

请注意,当您只想使用样式时,通常不需要withTheme: true选项。在此示例中需要这样做,因为在渲染中使用了主题的实际值。设置此选项将使theme通过类属性可用。即使未设置此选项,也应始终提供classes道具。

const useStyles = MaterialUI.withStyles((theme) => ({
  root: (props) => ({
    backgroundColor: props.backgroundColor,
    color: theme.color,
  }),
}), {withTheme: true});

const Component = useStyles(class extends React.Component {
  rendered = 0;

  render() {
    const {classes, theme, backgroundColor} = this.props;
    return (
      <div className={classes.root}>
        rendered {++this.rendered} times
        <br />
        color: {theme.color}
        <br />
        backgroundColor: {backgroundColor}
      </div>
    );
  }
});

function StressTest() {
  const [color, setColor] = React.useState('#8824bb');
  const [backgroundColor, setBackgroundColor] = React.useState('#eae2ad');

  const theme = React.useMemo(() => ({ color }), [color]);
  const valueTo = setter => event => setter(event.target.value);

  return (
    <MaterialUI.ThemeProvider theme={theme}>
      <div>
        <fieldset>
          <div>
            <label htmlFor="color">theme color: </label>
            <input
              id="color"
              type="color"
              onChange={valueTo(setColor)}
              value={color}
            />
          </div>
          <div>
            <label htmlFor="background-color">background-color property: </label>
            <input
              id="background-color"
              type="color"
              onChange={valueTo(setBackgroundColor)}
              value={backgroundColor}
            />
          </div>
        </fieldset>
        <Component backgroundColor={backgroundColor} />
      </div>
    </MaterialUI.ThemeProvider>
  );
}

ReactDOM.render(<StressTest />, document.querySelector("#root"));
<link rel="stylesheet" href="https://fonts.googleapis.com/css?family=Roboto:300,400,500,700&display=swap" />
<link rel="stylesheet" href="https://fonts.googleapis.com/icon?family=Material+Icons" />
<script src="https://unpkg.com/react@16/umd/react.production.min.js"></script>
<script src="https://unpkg.com/react-dom@16/umd/react-dom.production.min.js"></script>
<script src="https://unpkg.com/@material-ui/core@4/umd/material-ui.production.min.js"></script>
<div id="root"></div>

答案 4 :(得分:1)

对于类组件,您可以使用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)

答案 5 :(得分:0)

如何使用类组件在ClassName中添加多个类

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

const styles = theme => ({
  root: {
    backgroundColor: "red"
  },
  label: {
    backGroundColor:"blue"
 }
});

class ClassComponent extends Component {
  state = {
    searchNodes: ""
  };

  render() {
    const { classes } = this.props;//   
    return (
      <div className={classes.root + classes.label}>Hello!</div> //i want to add label style also with
    );
  }
}