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


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

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

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

然后在组件加载后

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的防抖。


文章作者: 2winter
文章链接: https://2winter.com
版权声明: 本博客所有文章除特別声明外,均采用 CC BY 4.0 许可协议。转载请注明来源 2winter !