基于FlatList的下拉刷新以及上拉加载更多

基于FlatList的下拉刷新以及上拉加载更多

    • 使用实例

import React, {useState} from 'react';
import {FlatList, Platform, RefreshControl} from 'react-native';

const FlatListComponent = ({
  data = [],
  onEndReachedThreshold = 0.1,
  renderItem = () => {}, //渲染列表
  keyExtractor = () => {}, //渲染列表key
  ListFooterComponent = () => {}, //添加底部
  ListHeaderComponent = () => {}, //添加头部
  onScroll = () => {}, //监听页面滚动
  onRefresh = () => {}, //下拉刷新
  onEndReached = () => {}, //上拉加载更多
}) => {
  const [refreshing, setRefreshing] = useState(false);
  const [iosDis, setIosDis] = useState(0);
  const pullDistanceThreshold = 150; // 下拉距离阈值

  const handleScroll = event => {
    const offsetY = event.nativeEvent.contentOffset.y;
    if (offsetY < -pullDistanceThreshold) {
      setIosDis(100);
    }
    onScroll && onScroll(offsetY);
  };

  const handleMomentumScrollEnd = event => {
    const {contentOffset} = event.nativeEvent;
    const isScrolling = contentOffset.y < 0;
    if (!isScrolling && iosDis >= 100) {
      setIosDis(0);
      onRefresh && onRefresh();
    }
  };

  const handleRefresh = () => {
    const systemType = Platform.OS;
    setRefreshing(true);
    setTimeout(() => {
      setRefreshing(false);
      // 模拟异步操作,例如发送网络请求
      if (systemType !== 'ios') {
        onRefresh && onRefresh();
      }
    }, 1500);
  };
  return (
    <>
      
        }
        onScroll={handleScroll}
        onMomentumScrollEnd={handleMomentumScrollEnd}
      />
    
  );
};

export default FlatListComponent;

使用实例

1.引入组件
import FlatListComponent from '../../componets/FlatListComponent';

2.使用
//监听页面滚动
  const [showSearchBar, setShowSearchBar] = useState(false);
  const monitorScrollHandle = offsetY => {
    // 当页面向上滚动超过100dp的时候,显示固定头部
    if (offsetY > 100) {
      setShowSearchBar(true);
    } else {
      setShowSearchBar(false);
    }
  };
  //下拉刷新
  const onPullDownRefresh = () => {
    console.log('[下拉刷新]');
  };

  //上拉加载更多
  const onReachBottom = () => {
    console.log('[上拉加载更多]');
  };
  //渲染头部数据
  const renderHeader = () => {
    return ;
  };
  //渲染底部数据
  const renderFooter = () => {
    return ;
  };


              item.type == '1' ? (
                
              ) : (
                
              )
            }
            keyExtractor={item => item.id.toString()}
            ListFooterComponent={renderFooter}
            ListHeaderComponent={renderHeader}
            onScroll={monitorScrollHandle}
            onEndReached={onReachBottom}
            onRefresh={onPullDownRefresh}
          />

你可能感兴趣的:(react-native,react.js,react,native)