【React】上拉加载更多,原生js的实现

本来是找的第三方库,但是都不好用,由于项目使用的布局是Absolute,导致各种bug,最后还是用原生吧。

给需要监听的组件设置一个Ref。

1
<div data-shoplist ref={e => (this.scroll = e)}>

然后在组件加载后

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
let loadTimer = null;
if (this.scroll) {
this.scroll.addEventListener("scroll", e => {
const {clientHeight, scrollHeight, scrollTop} = e.target;
const isBottom = scrollTop + clientHeight + 20 > scrollHeight;

if (isBottom) {
if(loadTimer){
clearTimeout(loadTimer)
loadTimer = setTimeout(loadMoreData, 300)
}else{
loadTimer = setTimeout(loadMoreData, 300)
}

}

});
}

这里加了300ms的防抖。