简介

        本文基于react实现下拉刷新效果,在下拉的时候会进入loading状态。

实现效果

React 实现下拉刷新效果-LMLPHP

效果如上图所示,在下拉到底部时候,会出现loading条,在处理完成后loading条消失。

具体代码

布局 & 逻辑

import {useRef, useState} from "react";

export const ScrollView = ({loadingComponent, contentComponent}) => {
    const LoadingComponent = loadingComponent;
    const ContentComponent = contentComponent;

    /**
     * 加载状态
     */
    const [loading, setLoading] = useState(false);

    /**
     * 滚动容器引用
     */
    const scrollRef = useRef(null);

    let contentStyle = {height: '30px', width:'100%', textAlign:'center', display:'none'};

    if (loading){ // 加载中显示
        contentStyle = {height: '30px', width:'100%', textAlign:'center'};
        scrollRef.current.scrollTop = 0; // 滚到头部
    }

    const handleScroll = ()=>{
        const {scrollTop} = scrollRef.current;

        if (scrollTop > 50 && !loading){
            setLoading(true); // 设置为加载中状态

            // 模拟数据加载
            setTimeout(()=>{
                setLoading(false); // 加载完成
            }, 3000)
        }

    }
    return (
        <div style={{height: '200px', overflow:'auto', width:'40%'}} ref={scrollRef} onScroll={handleScroll}>
            <div style={contentStyle}>
                <LoadingComponent/>
            </div>
            <div style={{height:'300px', width:'100%'}}>
                <ContentComponent/>
            </div>
        </div>
    )
}

使用demo


import {ScrollView} from "./component/scroll-view/ScrollView";

const App = ()=> {

    return (
       <ScrollView loadingComponent={Loading} contentComponent={Content}>
       </ScrollView>
    )
}
const Loading = ()=>{
    return <div>loading</div>
}
const Content  = ()=>{
    return <div> hello, world</div>
}



export default App;
03-17 14:57