2017-08-09 7 views
3

私は異なるセクションのウェブサイトを持っています。私はsegment.ioを使用して、ページ上のさまざまなアクションを追跡しています。ユーザーがdivの一番下にスクロールしたかどうかを検出するにはどうすればよいですか?私は以下を試してみましたが、ページ上をスクロールするとすぐに起動され、 divの最後に到達したときには表示されません。ユーザーがReact jでdivの下にスクロールしたときの検出

componentDidMount() { 
    document.addEventListener('scroll', this.trackScrolling); 
} 

trackScrolling =() => { 
    const wrappedElement = document.getElementById('header'); 
    if (wrappedElement.scrollHeight - wrappedElement.scrollTop === wrappedElement.clientHeight) { 
    console.log('header bottom reached'); 
    document.removeEventListener('scroll', this.trackScrolling); 
    } 
}; 

答えて

3

あなたが底部はまた、コンポーネントアンマウントのイベント( `document.removeEventListener`)を削除することをお勧めします

isBottom(el) { 
    return el.getBoundingClientRect().bottom <= window.innerHeight; 
} 

componentDidMount() { 
    document.addEventListener('scroll', this.trackScrolling); 
} 

trackScrolling =() => { 
    const wrappedElement = document.getElementById('header'); 
    if (this.isBottom(wrappedElement)) { 
    console.log('header bottom reached'); 
    document.removeEventListener('scroll', this.trackScrolling); 
    } 
}; 
+3

視聴されたかどうかを確認するためにel.getBoundingClientRect().bottomを使用することができます(' componentWillUnmount') –

関連する問題