我正在为我的 React 应用程序使用无限滚动,并具有检测我何时恰好位于页面底部的功能:
const [isFetching, setIsFetching] = useState(false);
// Fire Upon Reaching the Bottom of the Page
const handleScroll = () => {
if (
window.innerHeight +
Math.max(
window.pageYOffset,
document.documentElement.scrollTop,
document.body.scrollTop
) !==
document.documentElement.offsetHeight
)
return;
setIsFetching(true);
};
// Debounce the Scroll Event Function and Cancel it When Called
const debounceHandleScroll = debounce(handleScroll, 100);
useEffect(() => {
window.addEventListener("scroll", debounceHandleScroll);
return () => window.removeEventListener("scroll", debounceHandleScroll);
}, [debounceHandleScroll]);
debounceHandleScroll.cancel();
问题出在我在手机中加载我的页面时,似乎由于移动浏览器的选项卡或栏,它没有检测到页面底部,因此内容没有加载。
有什么方法可以检测到用户靠近底部并仅在此时触发该功能?
最佳答案
我认为 IntersectionObserver 可能就是您要找的东西。 您可以查看本教程以获取基本信息:https://dev.to/producthackers/intersection-observer-using-react-49ko
你也可以把它变成一个自定义的钩子(Hook),它接受一个 ref(在你的例子中,是页面底部的一个 n 元素):
import { useEffect, useState } from 'react';
const useIsVisible = ref => {
const [isIntersecting, setIntersecting] = useState(false);
const observer = new IntersectionObserver(([entry]) =>
setIntersecting(entry.isIntersecting),
);
useEffect(() => {
observer.observe(ref.current);
return () => {
observer.disconnect();
};
}, []);
return isIntersecting;
};
export default useIsVisible;
也许以下包也可以帮助您,它使无限滚动变得非常容易:
https://www.npmjs.com/package/react-infinite-scroll-component
关于javascript - 如何检测浏览器窗口是否为 "near"底部?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/70379478/