2016-08-16 110 views
2

我正在構建一個應用程序(ES6),我很好奇什麼是正確的方法來抓住滾動上/下滾動事件?React-listen向上/向下滾動?

我試過(npm)安裝react-scroll-listener,但我無法讓它與我的ES6類一起工作。

基本上我想:如果向上滾動,請執行此操作;如果向下滾動,請執行其他操作。

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; 

回答

2

這是一般建議對掛接到任何聽衆:

附上componentDidMount的東西,在卸裝componentWillUnmount

class Whatever extends Component { 
    componentDidMount() { 
    window.addEventListener('scroll', this.handleScroll) 
    } 

    componentWillUnmount() { 
    window.removeEventListener('scroll', this.handleScroll) 
    } 

    handleScroll(event) { 
    // do something like call `this.setState` 
    // access window.scrollY etc 
    }) 
} 
+0

謝謝!完善。從向下滾動區分滾動和向上滾動的最佳跨瀏覽器方式是什麼? –

+0

只記錄scrollY值並查看下一個是否小於或大於 – azium

+2

如何在隱藏溢出的元素上捕獲輪子事件? (即無需滾動,但仍希望將輪子事件用作觸發器)。 –