如何在 React JS 中添加 inview 事件?
像这样的事情:
<div inview={handleInView}></div>
我需要将其添加到页脚上,以便我可以在页面中加载更多新闻。 谢谢。
最佳答案
我最近写了一个这样的组件。当它出现在 View 中时,它会触发 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
};
关于javascript - React JS View 事件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35633134/