React JS inview事件

时间:2016-02-25 16:37:51

标签: javascript events reactjs

如何在 React JS 中添加 inview 事件?
像这样:

  

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

我需要在页脚上添加它,以便我可以在页面中加载更多新闻。 感谢。

2 个答案:

答案 0 :(得分:2)

我最近写了这样一个组件。当它进入视图时,它会触发onFetch道具(由更高阶的组件指定)。

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
};

答案 1 :(得分: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

中的工作情况