听向上/向下滚动? [英] Listen for scroll up / down?
本文介绍了听向上/向下滚动?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在构建一个应用程序 (ES6),我很好奇捕获向上/向下滚动事件的正确"方法是什么?
I'm building an app (ES6) and I'm curious what is the 'correct' way to catch scroll up / down events?
我尝试 (npm) 安装 react-scroll-listener,但我无法让它与我的 ES6 类一起工作.
I tried (npm) installing react-scroll-listener but I couldn't get it to work with my ES6 class.
基本上我想要:如果向上滚动,请执行此操作;如果向下滚动,请执行其他操作.
Basically I want: if scroll up, do this; if scroll down, do something else.
import React from 'react';
import config from '../config';
import StaticImageList from '../Common/StaticImageList';
import ScrollListener from 'react-scroll-listener';
class Album extends React.Component {
constructor(props){
super(props);
}
myScrollStartHandler(){
console.log('Scroll start');
}
myScrollEndHandler(){
console.log('Scroll end 300ms(default)');
}
componentDidMount(){
scrollListener.addScrollHandler('body', myScrollStartHandler, myScrollEndHandler );
}
render(){
return <StaticImageList />;
}
};
export default Album;
推荐答案
这是挂钩任何听众的一般建议:
This is general advice for hooking into any listeners:
在componentDidMount
中附加东西,在componentWillUnmount
class Whatever extends Component {
componentDidMount() {
window.addEventListener('scroll', this.handleScroll, { passive: true })
}
componentWillUnmount() {
window.removeEventListener('scroll', this.handleScroll)
}
handleScroll(event) {
// do something like call `this.setState`
// access window.scrollY etc
}
}
这篇关于听向上/向下滚动?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文