【问题标题】:How can I understand MaterialUI styled component?如何理解 MaterialUI 样式的组件?
【发布时间】:2019-05-22 21:27:57
【问题描述】:

我正在尝试了解如何使用 MaterialUI 将样式注入组件,但我很困惑!谁能解释我做错了什么?我阅读了文档,但老实说对我来说没有意义。什么是类?以及如何将 const 样式附加到组件 BeerList 中?

我的代码抛出错误“无法读取未定义类的属性。我知道我一定是从错误的道具中拉出来的。但我不知道如何修复它......

 import React from 'react';
import BeerListItem from './BeerListItem';
import PropTypes from 'prop-types';
import { withStyles } from '@material-ui/core/styles';
import GridList from '@material-ui/core/GridList';
import GridListTile from '@material-ui/core/GridListTile';
import GridListTileBar from '@material-ui/core/GridListTileBar';
import IconButton from '@material-ui/core/IconButton';
import StarBorderIcon from '@material-ui/icons/StarBorder';

const styles = theme => ({
    root: {
      display: 'flex',
      flexWrap: 'wrap',
      justifyContent: 'space-around',
     overflow: 'hidden',
     backgroundColor: theme.palette.background.paper,
    },
    gridList: {
      width: '100%',
      height: '100%',
      transform: 'translateZ(0)',
    },
    titleBar: {
      background:
        'linear-gradient(to bottom, rgba(0,0,0,0.7) 0%, ' +
        'rgba(0,0,0,0.3) 70%, rgba(0,0,0,0) 100%)'
      },

    icon: {
      color: 'white',
    },
  });

const BeerList = ({beers}) =>{
const {classes} = beers;
    const beerItems = beers.map((beer) => {
        return <BeerListItem  key={beer.id} beer = {beer}/> 
      });
      return (<div className={classes.root} >
       <GridList cellHeight={250} spacing={1} >
      {beerItems}
      </GridList>
      </div>);
    };


export default withStyles(styles)(BeerList);

【问题讨论】:

  • 控制台beers 道具。检查它是什么?然后解构classes
  • 我做到了。这只是一份 20 种啤酒的清单。我阅读了 GridList 上的文档,但我不明白 const {classes}= props 中的道具到底是什么,为什么不使用
    而是使用 classes.icon?

标签: css reactjs material-ui


【解决方案1】:

类从道具分解。 您需要对组件进行一些更改,例如:

const BeerList = (props) =>{
const {classes, beers} = props;

  // rest of your code
  return <div className={classes.root} >
    <GridList cellHeight={250} spacing={1} >
      {beerItems}
    </GridList>
  </div>
};

就是这样。

【讨论】:

  • 你救了我@Ikram!非常感谢!!
猜你喜欢
  • 2021-12-10
  • 2019-10-14
  • 2023-02-20
  • 1970-01-01
  • 2019-11-21
  • 2010-10-17
  • 2019-03-06
  • 2019-08-29
  • 2018-08-20
相关资源
最近更新 更多