Image on Material UI CardMedia
我在从CardMedia图像上的道具获取图像时遇到一些麻烦:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 | <Card className={classes.card}> <CardMedia className={classes.img} image={this.props.recipe.thumbnail} /> <CardContent className={classes.content}> <Typography gutterBottom variant="headline" component="h2"> {this.props.recipe.title} </Typography> <Typography component="p"> {this.props.recipe.ingredients} </Typography> </CardContent> <CardActions> <Button href={this.props.recipe.href} Recipe </Button> </CardActions> </Card> |
它只是不渲染所有图像;所有其他props值将按需渲染。
同样作为Material UI,我在JS css上指定了CardMedia高度。
有人知道为什么会这样吗?
好,有同样的问题。终于成功了。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 | const styles = { media: { height: 0, paddingTop: '56.25%', // 16:9, marginTop:'30' } }; <CardMedia className={classes.media} ***image={require('assets/img/bg2.jpg')}*** title="Contemplative Reptile" **style={styles.media}** /> |
您还可以检查:
https://codesandbox.io/s/9zqr09zqjo-无选项加载图像。图像位置是我的本地
我已经阅读了文档,还注意到您必须指定高度才能显示图像。尽管他们说您应该使用样式创建一个组件,但我觉得一种更简单的方法是直接使用样式道具:
1 2 3 4 5 | <CardMedia style={{height: 0, paddingTop: '56.25%'}} image={project.image} title="lorem ipsum" /> |
其他选择是先创建一个样式对象,然后按照文档所述用Style渲染组件:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 | const styles = { card: { maxWidth: 345, }, media: { height: 0, paddingTop: '56.25%', // 16:9 }, }; function SimpleMediaCard(props) { const { classes } = props; return ( <Card className={classes.card}> <CardMedia className={classes.media} image="/static/images/cards/contemplative-reptile.jpg" title="Contemplative Reptile" /> </Card> ); } export default withStyles(styles)(SimpleMediaCard); |
要在CardMedia上设置后备图片,您可以尝试以下操作:
1 2 3 4 5 6 7 8 9 10 | import FALLBACK_IMAGE from 'src/assets/images/fallback_image.png'; const onMediaFallback = event => event.target.src = FALLBACK_IMAGE; <CardMedia component="img" className={classes.media} image="/static/images/cards/contemplative-reptile.jpg" title="Contemplative Reptile" onError={onMediaFallback} /> |
我面临着同样的问题。
一个好的解决方法是在CardMedia主体内使用'img'元素和'src'属性,而不是将其作为属性传递给CardMedia。
1 2 3 | <CardMedia> <img src={this.props.recipe.thumbnail} alt="recipe thumbnail"/> </CardMedia> |
在将道具传递给班级时,我将图像路径作为对象发送。在您的情况下,假设配方是一个具有缩略图作为属性之一的对象。然后在父类中,我将prop编写为:
1 2 3 4 5 6 7 8 9 10 | ... recipe = { . . thumbnail: require('assets/images/img1.jpg'), //make sure the path of the image is relative to parent class where you are defining the prop . . } ... |
在这里,我将图像的路径作为对象发送。这对我有用。
在我的情况下,它在样式中将高度值(而不是0)更改后起作用了
不起作用:
1 2 3 4 5 6 7 8 9 | const styles = { card: { maxWidth: 345, }, media: { height: 0, paddingTop: '56.25%', // 16:9 }, }; |
工作时间:
1 2 3 4 5 6 7 8 9 | const styles = { card: { maxWidth: 345, }, media: { height:"300px" or"10em", paddingTop: '56.25%', // 16:9 }, }; |