UNPKG

vtils

Version:

一个面向业务的 JavaScript/TypeScript 实用程序库。

55 lines (53 loc) 1.85 kB
/** * Modified from https://github.com/karl-run/react-bottom-scroll-listener/blob/master/src/hook/index.tsx */ import { bindEvent, debounce } from "../utils/index.js"; import { useEffect, useRef } from 'react'; import { useLatest } from 'react-use'; /** * 立即触发一次回调,并且每当到达页面底部时触发回调。 * * @public * @param callback 回调 * @param offset 触底偏移量 * @returns 返回 */ export function useReachBottom(callback, offset) { if (offset === void 0) { offset = 0; } var containerRef = useRef(null); var latestCallback = useLatest(callback); useEffect(function () { var latestDebouncedCallback = debounce(function () { return latestCallback.current(); }, 200, { leading: true, trailing: true }); var unbindEvent = bindEvent(containerRef.current || window)('scroll', function () { if (this === window) { var scrollNode = document.scrollingElement || document.documentElement; var scrollContainerBottomPosition = Math.round(scrollNode.scrollTop + window.innerHeight); var scrollPosition = Math.round(scrollNode.scrollHeight - offset); if (scrollPosition <= scrollContainerBottomPosition) { latestDebouncedCallback(); } } else { var _scrollNode = containerRef.current; var _scrollContainerBottomPosition = Math.round(_scrollNode.scrollTop + _scrollNode.clientHeight); var _scrollPosition = Math.round(_scrollNode.scrollHeight - offset); if (_scrollPosition <= _scrollContainerBottomPosition) { latestDebouncedCallback(); } } }); // 立即触发一次回调 latestDebouncedCallback(); return function () { unbindEvent(); latestDebouncedCallback.cancel(); }; }, [offset]); return containerRef; }