【问题标题】:Image not displaying in material-ui CardMedia element图像未显示在 material-ui CardMedia 元素中
【发布时间】:2020-07-01 01:26:59
【问题描述】:

我创建了我在应用程序中遇到的问题的简化版本。

我有一个卡片组件(此处由 MyCardComponent 表示),我想将一个字符串 prop 与图像文件的位置一起传递到该组件中,并将其呈现在 material-ui Card 上的 CardMedia 元素中

但是图像没有出现,我如何让它渲染? .查看 CodeSandbox 中重新创建的问题

MyCardComponent.js

import React from "react";
import PropTypes from "prop-types";
import "./styles.css";
import { makeStyles } from "@material-ui/core/styles";
import { Card, CardMedia, CardContent } from "@material-ui/core";

const useStyles = makeStyles(theme => ({
  cardRootStyle: {
    minHeight: 300,
    maxHeight: 300
  },
  cardMediaStyle: {
    minHeight: 100,
    maxHeight: 100
  }
}));
export default function MyCardComponent(props) {
  const styles = useStyles();
  return (
    <>
      <Card
        classes={{
          root: styles.cardRootStyle
        }}
      >
        <CardContent>
          <CardMedia image={props.imagePath} />
        </CardContent>
      </Card>
    </>
  );
}

MyCardComponent.propTypes = {
  imagePath: PropTypes.string
};

我这样称呼MyCardComponent

<MyCardComponent imagePath='/static/sampleimages/cocacola.png'/>

【问题讨论】:

    标签: javascript css reactjs material-ui


    【解决方案1】:

    我发现了两个问题:

    1. 图片路径有问题。
    2. 你忘了使用paddingTop。阅读the docs

    Here an example.

    【讨论】:

    • 感谢您的示例。我现在可以看到我应该在我的应用程序的公共目录中拥有图像,而不是在该级别的它自己的静态目录中。现在一切正常??
    【解决方案2】:

    首先尝试使用

    导入您的图像
    import cocacola from 'whereveryourimageis/cocacola.png'
    

    那就这样用吧

    imagePath={cocacola}
    

    现在它就在那里!

    但不会出现,因为显然你的 .MuiCardMedia-root 的高度 = 0,所以你也应该处理它

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-10-20
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-01-29
      • 2021-07-15
      • 2021-05-04
      相关资源
      最近更新 更多