React 实现下拉刷新效果

简介

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

实现效果

效果如上图所示,在下拉到底部时候,会出现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;

相关推荐

  1. uniapp刷新

    2024-03-17 05:20:01       47 阅读
  2. uni-app自定义导航栏刷新实现

    2024-03-17 05:20:01       15 阅读
  3. 微信小程序实现刷新事件、上触底事件

    2024-03-17 05:20:01       41 阅读
  4. 微信scroll-view小程序实现加载刷新

    2024-03-17 05:20:01       29 阅读

最近更新

  1. TCP协议是安全的吗?

    2024-03-17 05:20:01       16 阅读
  2. 阿里云服务器执行yum,一直下载docker-ce-stable失败

    2024-03-17 05:20:01       16 阅读
  3. 【Python教程】压缩PDF文件大小

    2024-03-17 05:20:01       15 阅读
  4. 通过文章id递归查询所有评论(xml)

    2024-03-17 05:20:01       18 阅读

热门阅读

  1. Python列表详解

    2024-03-17 05:20:01       19 阅读
  2. 【C语言】打印1-100之间所有3的倍数的数字

    2024-03-17 05:20:01       19 阅读
  3. 使用API删除Gitlab Pipeline

    2024-03-17 05:20:01       19 阅读
  4. CSS2DObject 形成3D模型二维屏幕平面label

    2024-03-17 05:20:01       17 阅读
  5. Hive Sql获取含有特殊字符key的json数据

    2024-03-17 05:20:01       21 阅读