Mar*_*elo 2 reactjs material-ui
我在从CardMedia图像上的道具获取图像时遇到了一些麻烦:
<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>
Run Code Online (Sandbox Code Playgroud)
它只是不渲染所有图像。所有其他props值将按需渲染。同样作为Material UI,我已经在JS css上指定了CardMedia的高度。
有谁知道为什么会这样吗?
我阅读了文档,还注意到您必须指定显示图像的高度。尽管他们说您应该使用样式创建一个组件,但我觉得一种更简单的方法是直接使用样式道具:
<CardMedia
style={{height: 0, paddingTop: '56.25%'}}
image={project.image}
title="lorem ipsum"
/>
Run Code Online (Sandbox Code Playgroud)
其他选择是先创建一个样式对象,然后按照文档所述用Style渲染组件:
const styles = {
card: {
maxWidth: 345,
},
media: {
height: 0,
paddingTop: '56.25%', // 16:9
},
};
function SimpleMediaCard(props) {
const { classes } = props;
return (
<div>
<Card className={classes.card}>
<CardMedia
className={classes.media}
image="/static/images/cards/contemplative-reptile.jpg"
title="Contemplative Reptile"
/>
</Card>
</div>
);
}
export default withStyles(styles)(SimpleMediaCard);
Run Code Online (Sandbox Code Playgroud)
小智 7
要在 CardMedia 上设置后备图像,您可以尝试以下操作:
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}
/>
Run Code Online (Sandbox Code Playgroud)
好的,有同样的问题。终于成功了。
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}**
/>
Run Code Online (Sandbox Code Playgroud)
您还可以检查:https : //codesandbox.io/s/9zqr09zqjo-无选项加载图像。图片位置在我本地
小智 6
我面临着同样的问题。一个好的解决方法是在 CardMedia 主体内使用“img”元素和“src”属性,而不是将其作为属性传递给 CardMedia。
<CardMedia>
<img src={this.props.recipe.thumbnail} alt="recipe thumbnail"/>
</CardMedia>
Run Code Online (Sandbox Code Playgroud)
在将道具传递给类时,我将图像路径作为对象发送。在您的情况下,假设配方是一个以缩略图作为属性之一的对象。然后在父类中,我将 prop 写为:
...
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
.
.
}
...
Run Code Online (Sandbox Code Playgroud)
这里我将图像的路径作为对象发送。这对我有用。
从 4.9 => 4.12 更新后
添加component="img"道具
0(更新后它在 DOM 中具有高度,尽管将其设置为200px)
<CardMedia className={classes.pageMedia} component='img' image='/static/img.jpg' />
| 归档时间: |
|
| 查看次数: |
19807 次 |
| 最近记录: |