1 import {useEffect} from 'react';
 2 let observer;
 3 export default function useObserverHook(ele,callback,watch=[]) {
 4   useEffect(()=>{
 5     const node=document.querySelector(ele);
 6     if(node){
 7       observer=new IntersectionObserver(entries=>{
 8         callback&&callback(entries)
 9       })
10       observer.observe(node)
11     }
12     return ()=>{
13       if(node&&observer){
14         //解绑
15         observer.unobserve(node);
16         //停止监听
17         observer.disconnect();
18       }
19     }
20   },watch)
21 }
1 useObserverHook('#mkLoading',(entries)=>{//监听mkLoading元素
2   if(entries[0].isIntersecting&&!loading){//当出现在视线时entries[0].isIntersecting为true同时限制为为请求数据状态,然后通过改变pageNumber
3     setPage({//请求数据
4       ...page,
5       pageNum:page.pageNum+1
6     })
7   }
8 },null)
 1 let observer;
 2 export default function useImgHook(ele, callback, watch = []){
 3   useEffect(()=>{
 4     const nodes = document.querySelectorAll(ele);
 5     if(!isEmpty(nodes)){
 6       observer = new IntersectionObserver((entries)=>{
 7         callback && callback(entries);
 8         entries.forEach(item => {
 9           if(item.isIntersecting){
10             const dataSrc = item.target.getAttribute('data-src');
11             item.target.setAttribute('src', dataSrc);
12             observer.unobserve(item.target);
13           }
14         });
15       });
16       nodes.forEach(item => {
17         observer.observe(item);
18       });
19     }
20 
21     return () => {
22       if(!isEmpty(nodes) && observer){
23         observer.disconnect();
24       }
25     }
26   }, watch)
27 }
useImgHook('.itemImg', (enties)=>{}, null);
View Code
useImgHook('.itemImg', (enties)=>{}, null);

 

posted on 2020-12-18 17:20  小白学前端  阅读(184)  评论(0编辑  收藏  举报