Как стилизовать компоненты класса, используя makeStyles в интерфейсе материалов? - PullRequest
10 голосов
/ 03 июня 2019

Это самый маленький пример, другие также присваивают классы дочерним элементам.Когда я запускаю код ниже, я получаю, и я не могу найти ничего в документации 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;

Ответы [ 2 ]

11 голосов
/ 15 июня 2019

Привет, вместо использования ловушечного API, вы должны использовать 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);
0 голосов
/ 06 июля 2019

В результате мы перестали использовать компоненты класса и создали функциональные компоненты, используя useEffect() из Hooks API для методов жизненного цикла . Это позволяет вам по-прежнему использовать makeStyles() с методами жизненного цикла , не добавляя усложнения создания компонентов высшего порядка . Что гораздо проще.

Пример:

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