美文网首页
react 组件滚动到可视区域在加载

react 组件滚动到可视区域在加载

作者: clmll | 来源:发表于2019-06-26 11:53 被阅读0次
    import React,{ PureComponent } from 'react';
    
    
    export const getScrollTop = () => {
      let scroll_top = 0;
      if (document.documentElement && document.documentElement.scrollTop) {
        scroll_top = document.documentElement.scrollTop;
      }
      else if (document.body) {
        scroll_top = document.body.scrollTop;
      }
      return scroll_top;
    };
    
    const checkInPage = el => {
      const pageHeight = document.documentElement.clientHeight;
      const contentTop = el.getBoundingClientRect().top;
      const contentHeight = el.offsetHeight;
      return (contentTop < pageHeight && contentTop >= 0) || (contentTop < 0 && (contentTop + contentHeight > 0));
    };
    
    const lazyLoading = ({ minHeight = 0 }) => (ChildComponent) => {
      return class extends PureComponent{
    
        static defaultProps={
          lazyLoading:true
        };
    
        state = {
          visible:false
        };
    
        checkInPage = () => {
          let isVisible = checkInPage(this.el);
          let { visible } = this.state;
          if ( visible === true ){
            window.removeEventListener('scroll',this.checkInPage);
            return;
          }
          this.setState({ visible:isVisible });
        };
    
        componentDidMount(){
          if ( this.props.lazyLoading === false ){
            return;
          }
          setTimeout(()=>{ 
            this.checkInPage();
            window.addEventListener('scroll',this.checkInPage);
          },200)
        }
    
        componentWillUnmount(){
          if ( this.props.lazyLoading === false ){
            return;
          }
          window.removeEventListener('scroll',this.checkInPage);
        }
    
        render(){
    
          if ( this.props.lazyLoading === false ){
            return <ChildComponent {...this.props} />
          }
    
          return <div ref={el=>this.el=el} style={{ minHeight }} >
            { this.state.visible && <ChildComponent {...this.props} /> }
          </div>
        }
      }
    };
    
    export default lazyLoading;
    

    相关文章

      网友评论

          本文标题:react 组件滚动到可视区域在加载

          本文链接:https://www.haomeiwen.com/subject/agzqcctx.html