2016-02-25 68 views
0

如何添加調查事件React JS
事情是這樣的:React JS inview event

<div inview={handleInView}></div>

我需要添加它的頁腳,所以我可以加載頁面的詳細消息。 謝謝。

回答

0

您可以綁定滾動事件並測試元素的位置,這可以改變組件的狀態或觸發您需要的任何其他方法/事件。

爲了簡單起見,我已經在這裏使用了jQuery,通過使用ref來定位元素,但是沒有這個可以做到這一點。 React有一些內置滾動的東西,他們在這裏覆蓋它們http://blog.vjeux.com/2013/javascript/scroll-position-with-react.html。注意:鏈接很舊,所以我確定有更好的文檔。

var Component = React.createClass({ 
    getInitialState: function(){ 
    return { 
     text: 'Not in view' 
    } 
    }, 
    componentDidMount: function(){ 
    $(window).on('scroll', this.inview); 
    }, 
    inview: function() { 

    var $e = $(React.findDOMNode(this.refs.footer)), 
     $w = $(window), 
     wt = $w.scrollTop(), 
     wb = wt + $w.height(), 
     et = $e.offset().top, 
     eb = et + $e.height(); 

    var isVisible = eb >= wt && et <= wb; 

    this.setState({'text': isVisible ? 'In view' : 'Not in view'}); 
    }, 
    render: function(){ 
    return (
     <div> 
     <h1>{this.state.text}</h1> 
     <p>Scroll down</p> 
     <footer ref="footer">FOOTER</footer> 
     </div> 
    ) 
    } 
}); 

React.render(
    <Component />, 
    document.getElementById('react') 
); 

鏈接看到它在JSBIN here

+0

謝謝,你救了我的一天! – Ninosaurus

+0

不用擔心,很高興能幫到你! – OllieH

2

工作,我最近寫了這樣的一個組成部分。它觸發onFetch prop(由高階組件指定)。

import React, { Component, PropTypes } from 'react'; 
import { findDOMNode } from 'react-dom'; 
import classNames from 'classnames'; 
import { debounce } from 'underscore'; 

export default class ScrollLoader extends Component { 

    componentDidMount() { 
     this.scrollListener = debounce(this.fetchInView.bind(this), 200); 
     window.addEventListener('scroll', this.scrollListener); 
    } 

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

    fetchInView() { 
     const { loading, onFetch } = this.props; 
     const { top } = findDOMNode(this).getBoundingClientRect(); 
     const OFFSET = 50; // ensure the element is at least 50 pixels in view 

     if (!loading && top < window.innerHeight + OFFSET && typeof onFetch === 'function') { 
      onFetch(); 
     } 
    } 

    render() { 
     const { loading } = this.props; 

     return (
      <div className={classNames('scrollloader', { 'scrollloader-loading' : loading })} /> 
     ); 
    } 

} 

ScrollLoader.propTypes = { 
    loading: PropTypes.bool, 
    onFetch: PropTypes.func 
};