React实现懒加载组件

一、首先我是结合IntersectionObserver进行实现的,url:https://developer.mozilla.org/zh-CN/docs/Web/API/IntersectionObserver/IntersectionObserverx

先去结合MND文档可以尝试写一个demo,话不多说,下面是react的代码!

react:

这是图片示例

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"
];

组件示例 

const ImageLazy = () => {
    const observer: React.MutableRefObject = 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 
{ Urls.map(url => ) }
} export default ImageLazy

你可能感兴趣的:(react.js,前端,前端框架)