我注意到,在移动版的https://mail.google.com/中,即使在上下滚动你的电子邮件列表时,你也可以点击任何邮件,它就会打开。我想在我的应用程序中对react产生同样的效果,但我不知道如何实现它。每次滚动屏幕时,点击事件都会被阻止,只有在滚动停止后,您才能做您想做的事情。
发布于 2020-08-18 19:15:09
为了在滚动事件期间触发事件,必须通过useRef处理屏幕的滚动状态。如果您的最后一个屏幕位置与当前位置不同,则可以在滚动过程中触发某些内容。
在您的依赖项上使用此挂钩:
import { useRef, useLayoutEffect } from "react";
const isBrowser = typeof window !== `undefined`;
const getScrolledPosition = ({ element, useWindow }) => {
if (!isBrowser) return { x: 0, y: 0 };
const target = element ? element.current : document.body;
const position = target.getBoundingClientRect();
return useWindow
? { x: window.scrollX, y: window.scrollY }
: {
x: position.left,
y: position.top,
height: position.height,
bottom: position.bottom,
};
};
export const useScrollPosition = (effect, deps, element, useWindow, wait) => {
const position = useRef(getScrolledPosition({ useWindow }));
let throttleTimeout = null;
const callBack = () => {
const currPos = getScrolledPosition({ element, useWindow });
effect({ prevPos: position.current, currPos });
position.current = currPos;
throttleTimeout = null;
};
useLayoutEffect(() => {
const handleScroll = () => {
if (wait) {
if (throttleTimeout === null) {
throttleTimeout = setTimeout(callBack, wait);
}
} else {
callBack();
}
};
window.addEventListener("scroll", handleScroll);
return () => window.removeEventListener("scroll", handleScroll);
}, deps);
};下面是一个示例,说明如何在滚动期间调用此钩子并执行触发事件
const [visible, setVisible] = useState(true);
const [paintToolbar, setPaintToolbar] = useState(false);
useScrollPosition(
({ prevPos, currPos }) => {
const isShow = currPos.y > prevPos.y;
if (isShow !== visible) setVisible(isShow);
const below100vH = currPos.bottom <= 0;
!below100vH ? setPaintToolbar(false) : setPaintToolbar(true);
},
[paintToolbar, visible],
false,
false,
150
);如果您有任何疑问,请告诉我
=D
https://stackoverflow.com/questions/63466841
复制相似问题