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;
网友评论