Last active
August 3, 2021 12:19
-
-
Save TimRChen/df6ee0822318205593b3f6957d0a3882 to your computer and use it in GitHub Desktop.
react 版 useInfiniteScroll
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import { useRef, MutableRefObject } from 'react' | |
import { useUpdateEffect, useUnmount } from 'ahooks' | |
/** | |
* 采用Intersection Observer API 实现无限滚动 | |
* more_help: https://developer.mozilla.org/zh-CN/docs/Web/API/Intersection_Observer_API#intersection_observer_%E7%9A%84%E6%A6%82%E5%BF%B5%E5%92%8C%E7%94%A8%E6%B3%95 | |
* @author <[email protected]> | |
* @param target 目标元素,可在可增加列表末尾设置一个标志标签 | |
* @param callback 正在相交时执行回调,请注意!如果有一些耗时的操作需要执行,建议使用 Window.requestIdleCallback() 方法 | |
* @param options IntersectionObserver()构造函数的 options 对象,可选值参考:https://developer.mozilla.org/zh-CN/docs/Web/API/IntersectionObserver/IntersectionObserver#%E5%8F%82%E6%95%B0 | |
*/ | |
export default function useInfiniteScroll( | |
callback: MutableRefObject<() => void>, | |
options: IntersectionObserverInit = {}, | |
target: Element | null, | |
) { | |
const observer: MutableRefObject<IntersectionObserver | null> = useRef(null) | |
const executor = ([entry]: IntersectionObserverEntry[]) => { | |
// 目标元素是否进入可视区域 | |
if (entry && entry.isIntersecting) callback.current() | |
} | |
useUpdateEffect(() => { | |
if (!target) { | |
throw new Error('intersectTarget "target" must be a Element or a React MutableRefObject') | |
} | |
observer.current = new IntersectionObserver(executor, options) | |
observer.current.observe(target) | |
}, [options.root, target]) | |
useUnmount(() => observer.current && observer.current.disconnect()) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
用法: