【发布时间】:2020-11-12 15:54:59
【问题描述】:
我需要动态知道图像的宽度和高度,所以我使用了Image 对象和onload 事件函数。加载所有图像后,我的组件应该重新渲染并将高度和宽度值传递给子组件(<PhotoGallery />)。
这是我的解决方案。
import React, { useState, useRef } from "react";
import PhotoGallery from "react-photo-gallery";
import Lightbox from "react-image-lightbox";
import { makeStyles, createStyles, Theme, Grid, Button } from "@material-ui/core";
import { PhotoSharp } from "@material-ui/icons";
type Props = {
photoSrc: string[];
};
type PhotoGalleryImageType = {
src: string;
width: number;
height: number;
};
export default function ProjectGallery(props: Props) {
const [isLoading, setIsLoading] = useState(true);
const images = useRef<PhotoGalleryImageType[]>([]);
props.photoSrcSet.forEach((src) => {
var photo = new Image();
photo.src = src;
photo.onload = () => {
if (!images.current.some((v) => v.src === src)) {
images.current.push({ src: src, width: photo.naturalWidth, height: photo.naturalHeight });
}
if (images.current.length === props.photoSrcSet.length) {
setIsLoading(false);
}
};
});
if (isLoading) {
return <div>"loading.."</div>;
}
return (
<Grid container justify="center" direction="column">
<Grid item>
<PhotoGallery photos={images.current} />
</Grid>
</Grid>
);
}
不过我觉得应该有更好的办法,因为如果没有if (!images.current.some((v) => v.src === src))声明,图片src就有重复值。
你有什么建议吗?
【问题讨论】:
标签: javascript reactjs react-hooks