以下组件可完美运行文件。我想显示一个微调框,直到图像加载完毕。我该怎么办?
import React from 'react';
import { makeStyles } from '@material-ui/core/styles';
import Card from '@material-ui/core/Card';
import Image from 'material-ui-image';
import CardActionArea from '@material-ui/core/CardActionArea';
import CardContent from '@material-ui/core/CardContent';
import CardMedia from '@material-ui/core/CardMedia';
import Typography from '@material-ui/core/Typography';
/**
* Media is a Card, with an image / video and a caption. url of the media is hidden from the user,
* but the user can click it to open it in a new browser
*/
const useStyles = makeStyles({
card: {
margin: '0.5rem',
maxWidth: '25%'
}
});
const Media = ({ url, caption }: any) => {
const classes = useStyles();
return (
<Card className={classes.card}>
<CardActionArea>
<CardMedia component="img" alt={caption} height="140" image={url} title={caption} />
<CardContent>
<Typography variant="body2">{caption}</Typography>
</CardContent>
</CardActionArea>
</Card>
);
};
export default Media;
答案 0 :(得分:0)
Material-UI CardMedia component将图像显示为背景图像,因此您将无法访问DOM onLoad
标记上的<img>
属性。您可以选择使用<img>
,如下所示:
添加到您的导入中
import CircularProgress from '@material-ui/core/CircularProgress';
添加到您的样式:
media: {
width: '100%',
height: 140,
},
progress: {
# center spinner
}
向组件添加状态和onLoad处理程序:
const [loaded, setLoaded] = React.useState(false);
function handleImageLoad() {
setLoaded(true);
}
将您的CardMedia替换为:
{loaded ? (
<img
className={classes.media}
src={url}
alt={caption}
onLoad={handleImageLoad}
/>
) : (
<div className={classes.progress}>
<CircularProgress color="secondary" />
</div>
)}