如何在Material UI中使用makeStyles设置类组件的样式?

时间:2019-06-03 17:41:58

标签: reactjs material-ui

这是最小的示例,其他示例也将类分配给子项。当我运行下面的代码时,我得到了,并且在MUI的文档中找不到任何显示类组件样式的其他方法。我们需要能够访问类的生命周期方法和状态。

Invalid hook call. Hooks can only be called inside of the body of a function component. This could happen for one of the following reasons:
1. You might have mismatching versions of React and the renderer (such as React DOM)
2. You might be breaking the Rules of Hooks
3. You might have more than one copy of React in the same app
    import React, { Component } from 'react';
    import { Redirect } from 'react-router-dom';

    import { Container, makeStyles } from '@material-ui/core';

    import LogoButtonCard from '../molecules/Cards/LogoButtonCard';

    const useStyles = makeStyles(theme => ({
      root: {
        display: 'flex',
        alignItems: 'center',
        justifyContent: 'center',
      },
    }));

    const classes = useStyles();

    class Welcome extends Component {
      render() {
        if (this.props.auth.isAuthenticated()) {
          return <Redirect to="/" />;
        }
        return (
          <Container maxWidth={false} className={classes.root}>
            <LogoButtonCard
              buttonText="Enter"
              headerText="Welcome to PlatformX"
              buttonAction={this.props.auth.login}
            />
          </Container>
        );
      }
    }

    export default Welcome;

7 个答案:

答案 0 :(得分:48)

我用withStyles代替了makeStyle

EX:

import { withStyles } from '@material-ui/core/styles';
import React, {Component} from "react";

const useStyles = theme => ({
        root: {
           flexGrow: 1,
         },
  });

class App extends Component {
       render() {
                const { classes } = this.props;
                return(
                    <div className={classes.root}>
                       Test
                </div>
                )
          }
} 

export default withStyles(useStyles)(App)

答案 1 :(得分:11)

您好,而不是使用hook API,您应该使用here

中提到的高阶组件API

我将修改文档中的示例以适合您对类组件的需求

import React from 'react';
import PropTypes from 'prop-types';
import { withStyles } from '@material-ui/styles';
import Button from '@material-ui/core/Button';

const styles = theme => ({
  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',
  },
});

class HigherOrderComponent extends React.Component {

  render(){
    const { classes } = this.props;
    return (
      <Button className={classes.root}>Higher-order component</Button>
      );
  }
}

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

export default withStyles(styles)(HigherOrderComponent);

答案 2 :(得分:2)

useStyles是一个React钩子,应在功能组件中使用,不能在类组件中使用。

From React:

通过钩子,您可以使用状态和其他React功能,而无需编写 课。

另外,您应该像这样呼叫useStyles钩子inside your function

function Welcome() {
  const classes = useStyles();
...

如果要使用钩子,这是将您的简短类组件更改为功能组件;

import React from "react";
import { Container, makeStyles } from "@material-ui/core";

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

function Welcome() {
  const classes = useStyles();
  return (
    <Container className={classes.root}>
      <h1>Welcome</h1>
    </Container>
  );
}

export default Welcome;

↓CodeSandBox上的

?↓

Edit React hooks

答案 3 :(得分:0)

我们最终使用类组件停止了工作,并从using useEffect()创建了功能组件Hooks API for lifecycle methods。这样,您仍可以将makeStyles()与生命周期方法without adding the complication of making Higher-Order Components一起使用。这要简单得多。

示例:

import React, { useEffect } from 'react';
import { Redirect } from 'react-router-dom';

import { Container, makeStyles } from '@material-ui/core';

import LogoButtonCard from '../molecules/Cards/LogoButtonCard';

const useStyles = makeStyles(theme => ({
  root: {
    display: 'flex',
    alignItems: 'center',
    justifyContent: 'center',
  },
}));

const classes = useStyles();

const Welcome = () => {

  useEffect(() => {
    // Stuff you'd normally execute using ComponentDidMount here
  }, []);

  if (this.props.auth.isAuthenticated()) {
    return <Redirect to="/" />;
  }
  return (
    <Container maxWidth={false} className={classes.root}>
      <LogoButtonCard
        buttonText="Enter"
        headerText="Welcome to PlatformX"
        buttonAction={this.props.auth.login}
      />
   </Container>
   );
  }
}

export default Welcome;

答案 4 :(得分:0)

另一种解决方案可用于类组件- 只需使用MuiThemeProvider覆盖默认的MUI主题属性。 与其他方法相比,这将提供更大的灵活性-您可以在父组件中使用多个MuiThemeProvider。

简单步骤:

  1. 将MuiThemeProvider导入您的类组件
  2. 将createMuiTheme导入您的类组件
  3. 创建新主题
  4. 使用MuiThemeProvider和自定义主题包装要设置样式的目标MUI组件

请检查此文档以获取更多详细信息: https://material-ui.com/customization/theming/

import React from 'react';
import PropTypes from 'prop-types';
import Button from '@material-ui/core/Button';

import { MuiThemeProvider } from '@material-ui/core/styles';
import { createMuiTheme } from '@material-ui/core/styles';

const InputTheme = createMuiTheme({
    overrides: {
        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',
        },
    }
});

class HigherOrderComponent extends React.Component {

    render(){
        const { classes } = this.props;
        return (
            <MuiThemeProvider theme={InputTheme}>
                <Button className={classes.root}>Higher-order component</Button>
            </MuiThemeProvider>
        );
    }
}

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

export default HigherOrderComponent;

答案 5 :(得分:0)

您正在函数外部调用 useStyles 钩子。这就是为什么

答案 6 :(得分:-1)

代替将类转换为函数,一个简单的步骤是创建一个函数,以包含使用“类”的组件的jsx,在您的情况下为<container></container>,然后在内部调用此函数返回class render()作为标记。这样,您就可以从类中移出函数。它对我来说很完美。在我的情况下,这是一个<table>,我将其移到外部的TableStmt函数中,并在渲染器内部将该函数称为<TableStmt/>