功能簡介
useReachBottom
?是一個 React 自定義 Hook,支持監聽頁面(body)或任意可滾動元素(如 div)是否滾動到底部。它能幫助你在用戶滑動到底部時觸發加載更多、顯示提示等操作,極大提升前端交互體驗。
亮點
- 通用性強:支持監聽整個頁面,也支持監聽任意傳入的滾動容器。
- 兼容性好:內部對 scrollTop/scrollHeight 取值做了兼容處理,適配主流瀏覽器。
- 易用性高:API 簡單,直接返回是否到底部的布爾值。
- 可自定義偏移:支持 offset 參數,靈活控制觸發時機。
- 無第三方依賴:純 React 實現,體積小巧。
使用場景
- 無限滾動加載:用戶滑動到底部時自動加載更多內容。
- 滾動提示:如“已到頁面底部”提示條。
- 局部滾動區域監聽:如聊天窗口、評論區、彈窗等自定義滾動容器。
- 數據上報:統計用戶是否瀏覽到頁面底部。
使用示例
1. 監聽頁面(body)滾動到底部
import useReachBottom from "../hooks/useReachBottom";function PageScrollDemo() {const isBottom = useReachBottom();return (<div><div>{isBottom ? "已到頁面底部" : "未到頁面底部"}</div>{/* 內容足夠撐開頁面高度 */}{Array.from({ length: 20 }).map((_, i) => (<div key={i}>內容 {i + 1}</div>))}</div>);
}
2. 監聽指定 div 元素滾動到底部
import { useRef } from "react";
import useReachBottom from "../hooks/useReachBottom";function DivScrollDemo() {const divRef = useRef();const isBottom = useReachBottom(divRef);return (<div><divref={divRef}style={{ height: 200, overflow: "auto", border: "1px solid #ccc" }}>{Array.from({ length: 10 }).map((_, i) => (<div key={i}>行 {i + 1}</div>))}</div><div>{isBottom ? "已到div底部" : "未到div底部"}</div></div>);
}
useReachBottom 源碼
import { useEffect, useState } from "react";export default function useReachBottom(targetRef = null, offset = 0) {const [isBottom, setIsBottom] = useState(false);useEffect(() => {const element = targetRef?.current || document.documentElement;function handleScroll() {let scrollTop, scrollHeight, clientHeight;if (targetRef?.current) {scrollTop = element.scrollTop;scrollHeight = element.scrollHeight;clientHeight = element.clientHeight;} else {// 兼容所有主流瀏覽器scrollTop = Math.max(window.scrollY,document.documentElement.scrollTop,document.body.scrollTop);scrollHeight = Math.max(document.documentElement.scrollHeight,document.body.scrollHeight);clientHeight = window.innerHeight;}if (scrollHeight > clientHeight) {setIsBottom(scrollTop + clientHeight >= scrollHeight - 2 - offset);} else {setIsBottom(false);}}const scrollTarget = targetRef?.current || window;scrollTarget.addEventListener("scroll", handleScroll);handleScroll();return () => {scrollTarget.removeEventListener("scroll", handleScroll);};}, [targetRef, offset]);return isBottom;
}
?React 自定義Hook之頁面或元素滾動到底部監聽 Hook-useReachBottom - 高質量源碼分享平臺-免費下載各類網站源碼與模板及前沿動態資訊