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 组件滚动到可视区域在加载
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。
推荐阅读更多精彩内容
- 现象:滚动条在底部触发两次加载事件 当滚动条在底部显示时 滚动分页代码实现 火狐bug:当滚动条显示在页面底部时,...