1. 准备测试数据
const Urls: string[]=[
"https://img95.699pic.com/photo/50070/5999.jpg_wh860.jpg",
"https://pic3.zhimg.com/v2-d1f733345b0d11ea4d1bde0e2511dbc8_720w.jpg?source=172ae18b",
"https://ts1.cn.mm.bing.net/th/id/R-C.b2deabf4f73362fdeded6ebb1759e6d5?rik=QTdjsA3RyD4v4g&riu=http%3a%2f%2fn.sinaimg.cn%2fsinacn20107%2f549%2fw600h749%2f20190427%2f07db-hvvuiyp2168388.jpg&ehk=ea6ytlOusTMhUxs4TgDNYQqymM8voeFn9db9ZiNcMOk%3d&risl=&pid=ImgRaw&r=0"];
2. 封装组件
const ImageLazy = () => {
const observer: React.MutableRefObject<any> = useRef();
useEffect(() => {
observer.current = new IntersectionObserver(entries => {
entries.forEach((item: any) => {
if (item.intersectionRatio > 0) {
myLazy(item.target)
}
})
}, {
root: document.querySelector('#lazyImgDeom')
})
handleImgShow();
return () => {
observer.current.disconnect();
};
}, [])
const myLazy = (dom:HTMLImageElement) => {
if (!dom.src || dom.src !== dom.dataset.src) {
dom.src = dom.dataset.src as string;
}
dom.onload = () => {
dom.style.backgroundColor = '';
dom.style.aspectRatio = '';
}
}
const handleImgShow = useCallback(() => {
const list = [...(document.getElementById("imgList") as HTMLElement).getElementsByTagName("img")];
list.forEach(img => observer.current.observe(img))
}, [])
return <div className={styles.lazyImgDeom} id="lazyImgDeom">
<div className={styles.imgList} id="imgList">
{
Urls.map(url => <img className={styles.imgItem} data-src={url} key={url} />)
}
</div>
</div>
}
export default ImageLazy