3 回答
TA贡献1827条经验 获得超8个赞
我会创建一个Image组件来处理它自己的相关状态。然后在这个组件内,我会使用IntersectionObserverAPI 来判断图像的容器在用户浏览器上是否可见。
我会isLoading和isInview状态,isLoading将永远true直到isInview更新到true.
而当isLoadingis时true,我会使用nullas 作为src图像并显示占位符。
src仅在容器在用户浏览器上可见时加载。
function Image({ src }) {
const [isLoading, setIsLoading] = useState(true);
const [isInView, setIsInView] = useState(false);
const root = useRef(); // the container
useEffect(() => {
// sets `isInView` to true until root is visible on users browser
const observer = new IntersectionObserver(onIntersection, { threshold: 0 });
observer.observe(root.current);
function onIntersection(entries) {
const { isIntersecting } = entries[0];
if (isIntersecting) { // is in view
observer.disconnect();
}
setIsInView(isIntersecting);
}
}, []);
function onLoad() {
setIsLoading((prev) => !prev);
}
return (
<div
ref={root}
className={`imgWrapper` + (isLoading ? " imgWrapper--isLoading" : "")}
>
<div className="imgLoader" />
<img className="img" src={isInView ? src : null} alt="" onLoad={onLoad} />
</div>
);
}
我还会有 CSS 样式来切换占位符和图像的display属性。
.App {
--image-height: 150px;
--image-width: var(--image-height);
}
.imgWrapper {
margin-bottom: 10px;
}
.img {
height: var(--image-height);
width: var(--image-width);
}
.imgLoader {
height: 150px;
width: 150px;
background-color: red;
}
/* container is loading, hide the img */
.imgWrapper--isLoading .img {
display: none;
}
/* container not loading, display img */
.imgWrapper:not(.imgWrapper--isLoading) .img {
display: block;
}
/* container not loading, hide placeholder */
.imgWrapper:not(.imgWrapper--isLoading) .imgLoader {
display: none;
}
现在我的父组件将执行对所有图像 url 的请求。它也有自己的isLoading状态,当设置时true会显示自己的占位符。当图像 url 的请求得到解决时,我将映射到每个 url 以呈现我的Image组件。
export default function App() {
const [imageUrls, setImageUrls] = useState([]);
const [isLoading, setIsLoading] = useState(true);
useEffect(() => {
fetchImages().then((response) => {
setImageUrls(response);
setIsLoading((prev) => !prev);
});
}, []);
const images = imageUrls.map((url, index) => <Image key={index} src={url} />);
return <div className="App">{isLoading ? "Please wait..." : images}</div>;
}
TA贡献1860条经验 获得超9个赞
有用于此的库,但如果您想推出自己的库,则可以使用IntersectionObserver
,如下所示:
const { useState, useRef, useEffect } = React;
const LazyImage = (imageProps) => {
const [shouldLoad, setShouldLoad] = useState(false);
const placeholderRef = useRef(null);
useEffect(() => {
if (!shouldLoad && placeholderRef.current) {
const observer = new IntersectionObserver(([{ intersectionRatio }]) => {
if (intersectionRatio > 0) {
setShouldLoad(true);
}
});
observer.observe(placeholderRef.current);
return () => observer.disconnect();
}
}, [shouldLoad, placeholderRef]);
return (shouldLoad
? <img {...imageProps}/>
: <div className="img-placeholder" ref={placeholderRef}/>
);
};
ReactDOM.render(
<div className="scroll-list">
<LazyImage src='https://i.insider.com/536a52d9ecad042e1fb1a778?width=1100&format=jpeg&auto=webp'/>
<LazyImage src='https://www.denofgeek.com/wp-content/uploads/2019/12/power-rangers-beast-morphers-season-2-scaled.jpg?fit=2560%2C1440'/>
<LazyImage src='https://i1.wp.com/www.theilluminerdi.com/wp-content/uploads/2020/02/mighty-morphin-power-rangers-reunion.jpg?resize=1200%2C640&ssl=1'/>
<LazyImage src='https://m.media-amazon.com/images/M/MV5BNTFiODY1NDItODc1Zi00MjE2LTk0MzQtNjExY2I1NTU3MzdiXkEyXkFqcGdeQXVyNzU1NzE3NTg@._V1_CR0,45,480,270_AL_UX477_CR0,0,477,268_AL_.jpg'/>
</div>,
document.getElementById('app')
);
.scroll-list > * {
margin-top: 400px;
}
.img-placeholder {
content: 'Placeholder!';
width: 400px;
height: 300px;
border: 1px solid black;
background-color: silver;
}
<div id="app"></div>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.13.1/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.13.1/umd/react-dom.production.min.js"></script>
此代码让它们在屏幕上显示占位符后立即加载,但如果您想要更大的检测余量,则可以调整 的rootMargin选项,IntersectionObserver以便它在仍然略微离开屏幕的情况下开始加载。
TA贡献1798条经验 获得超3个赞
将响应数据映射到“isLoading”布尔值数组,并更新回调以获取索引并更新特定的“isLoading”布尔值。
function Sample() {
const [items, setItems] = useState([]);
const [imgLoading, setImgLoading] = useState([]);
useEffect(() => {
axios.get(url).then((response) => {
const { data } = response;
setItems(data);
setImgLoading(data.map(() => true));
});
}, []);
return items.map((item, index) => (
<img
src={item.imageUrl}
onLoad={() =>
setImgLoading((loading) =>
loading.map((el, i) => (i === index ? false : el))
)
}
/>
));
}
添加回答
举报