如何检测 React 中已加载的图像
当我在 Web 应用程序中执行手动深度链接钩子时,自动向下滚动到特定部分会导致图像加载延迟。
如何在 React 中执行任何操作之前检测图像的加载问题?下一个钩子使用eventListener
withload
和error
事件,并检测JavaScript 的HTMLImageElement.complete属性,以确定特定包装器元素中的所有图像是否都已完成。
import { useState, useEffect, RefObject } from "react";
export const useOnLoadImages = (ref: RefObject<HTMLElement>) => {
const [status, setStatus] = useState(false);
useEffect(() => {
const updateStatus = (images: HTMLImageElement[]) => {
setStatus(
images.map((image) => image.complete).every((item) => item === true)
);
};
if (!ref?.current) return;
const imagesLoaded = Array.from(ref.current.querySelectorAll("img"));
if (imagesLoaded.length === 0) {
setStatus(true);
return;
}
imagesLoaded.forEach((image) => {
image.addEventListener("load", () => updateStatus(imagesLoaded), {
once: true
});
image.addEventListener("error", () => updateStatus(imagesLoaded), {
once: true
});
});
return;
}, [ref]);
return status;
};
注意:添加这两者非常重要load
,error
以避免页面加载后出现任何阻塞。
根据complete
prop 的文档,如果满足以下任何一项,则认为图像已完全加载:
- src 和 srcset 属性均未指定。srcset 属性不存在,且 src 属性(虽然指定了)为空字符串 ("")。
- 图像资源已完全获取并已排队等待渲染/合成。
- 图像元素先前已确定图像完全可用并可供使用。
- 图像“损坏”;即由于错误或图像加载被禁用而导致图像加载失败。
要使用它,您必须传递一个 ref 包装器来限制搜索图像。
import { useRef } from "react";
import { useOnLoadImages } from "./hooks/useOnLoadImages";
import "./styles.css";
export default function App() {
const wrapperRef = useRef<HTMLDivElement>(null);
const imagesLoaded = useOnLoadImages(wrapperRef);
return (
<div className="App" ref={wrapperRef}>
<h2>How to detect images loaded in React</h2>
<div>
<p>{!imagesLoaded ? "Loading images..." : "Images loaded"}</p>
<img src="https://source.unsplash.com/1600x900/?nature" alt="nature" />
<img src="https://source.unsplash.com/1600x900/?water" alt="water" />
<img src="https://source.unsplash.com/1600x900/?animal" alt="animal" />
<img src="https://source.unsplash.com/1600x900/?lake" alt="lake" />
<img src="https://source.unsplash.com/1600x900/?life" alt="life" />
</div>
</div>
);
}
这里有一个演示链接(重新加载内部浏览器)
如果您喜欢这篇文章,请关注我:
文章来源:https://dev.to/alejomartinez8/how-to-detect-images-loaded-in-react-39fa