【发布时间】:2019-12-02 10:16:26
【问题描述】:
我正在尝试实现整页滚动。我的问题是车轮事件经常触发两次。 我在 vanilla js 上实现了它,并且效果很好。
const [ index, setIndex ] = useState(0);
const sectionWrapper = useRef();
const animationBreak = 750;
const maxIndex = 2;
let lastTime = 0;
useEffect(
() => {
const handleWheel = e => {
const sections = sectionWrapper.current.children;
const wheelDirection = e.wheelDelta;
const currentTime = new Date().getTime();
const isAnimationEnable = currentTime - lastTime > animationBreak;
if (!isAnimationEnable) return;
if (wheelDirection < 0 && index < maxIndex) {
setIndex(index + 1);
}
if (wheelDirection > 0 && index > 0) {
setIndex(index - 1);
}
sections[index].scrollIntoView({ behavior: 'smooth' });
lastTime = currentTime;
};
window.addEventListener('wheel', handleWheel);
return () => window.removeEventListener('wheel', handleWheel);
},
[ index ]
);
我尝试使用 lodash 的方法,如油门或去抖动。不适合我。
【问题讨论】:
标签: javascript reactjs dom-events react-hooks mousewheel