未定义this.props.classes中的Material-UI withStyles道具

时间:2019-07-11 05:27:50

标签: reactjs material-ui

我在Create React App应用程序中有两个React组件,一个父组件(App.js)和一个子组件(QuoteMachine.js)。 我在App.js中成功应用了withStyles HOC API,但是当我使用相同的格式在QuoteMachine.js中添加一种格式时,将this.props.classes.card作为属性传递给Material-UI Card组件实例导致了TypeError无法读取未定义的属性“ props”。 将withStyles HOC包含在多个组件中是否有问题?我应该改用ThemeProvider吗?

QuoteMachine.js:

import React from 'react';
import Button from '@material-ui/core/Button';
import Typography from '@material-ui/core/Typography';
import Card from '@material-ui/core/Card';
import CardActions from '@material-ui/core/CardActions';
import CardContent from '@material-ui/core/CardContent';
import './QuoteMachine.css';
import { withStyles } from '@material-ui/core/styles';

const styles = {
  card: {
    padding: '30px'
  }
};

// Parentheses around function body is implicit return
const QuoteMachine = (props) => (
  <Card className={this.props.classes.card}>
    <CardContent>
      {props.isDoneFetching ?
        (
          <Typography>
            <p className="quote">{props.randomQuote().quote}</p>
            <p className="author">–{props.randomQuote().author}</p>
          </Typography>
        ) : 'Loading...'}
    </CardContent>

    <CardActions>
      <Button
        size="large"
        onClick={props.nextRandomQuote}
      >
        Next
      </Button>
    </CardActions>
  </Card>
)

export default withStyles(styles)(QuoteMachine);

App.js:

import React, { Component } from 'react';
import QuoteMachine from './QuoteMachine';
import 'typeface-roboto'; // From Material-UI
import { Grid } from '@material-ui/core';
import { withStyles } from '@material-ui/core/styles';
import backgroundImage from './dawn.jpg';

const styles = {
  // container is root component (set in Grid component instance)
  container: {
    display: 'flex',
    alignItems: 'center',
    height: '100vh',
    background: `url(${backgroundImage}) center`,
    backgroundSize: 'cover', // Using this in background causes issues
  }
};

class App extends Component {
  constructor(props) {
    super(props);
    ...
  }

  ....

  render() {
    return (
      <Grid
        id="quote-box"
        className={this.props.classes.container}
        justify="center"
        container
      >
        <Grid xs={11} lg={8} item>
          <QuoteMachine
            isDoneFetching={this.state.isDoneFetching}
            randomQuote={this.randomQuote}
            nextRandomQuote={this.nextRandomQuote}
          />
        </Grid>
      </Grid>
    );
  }
}

export default withStyles(styles)(App);

1 个答案:

答案 0 :(得分:1)

由于QuoteMachine是功能组件,因此它没有this实例,并且从参数到功能组件都可以使用props。您将访问类似的类

<Card className={props.classes.card}>