react native封装ScrollView,实现(滑到底部)和(滑到顶部+手指继续向下滑)时拉取新数据
在React Native中,可以通过监听ScrollView
的滚动事件来实现在到达顶部或者底部时进行特定操作。以下是一个简单的例子,展示了如何封装ScrollView
组件以实现这一功能:
import React, { useRef, useState, useEffect } from 'react';
import { ScrollView, StyleSheet, Text, View } from 'react-native';
const InfiniteScrollView = ({ onReachBottom, onReachTop, children }) => {
const scrollViewRef = useRef(null);
const [isLoading, setIsLoading] = useState(false);
const handleScroll = () => {
if (!scrollViewRef.current) return;
const contentHeight = scrollViewRef.current.contentSize.height;
const scrollPosition = scrollViewRef.current.scrollAboveSpacer;
const insetTop = scrollViewRef.current.contentInset.top;
const isAtTop = (scrollPosition > insetTop) && (scrollPosition < insetTop + 1);
const isAtBottom = (contentHeight - scrollPosition) < 1;
if (isAtBottom && onReachBottom && !isLoading) {
setIsLoading(true);
onReachBottom().then(() => {
setIsLoading(false);
});
}
if (isAtTop && onReachTop && !isLoading) {
setIsLoading(true);
onReachTop().then(() => {
setIsLoading(false);
});
}
};
useEffect(() => {
const subscription = scrollViewRef.current?.addListener('scroll', handleScroll);
return () => subscription?.remove();
}, []);
return (
<ScrollView
ref={scrollViewRef}
onContentSizeChange={handleScroll}
scrollEventThrottle={16}
contentInset={{ top: 0, bottom: 100 }}
>
{children}
{isLoading && <Text>Loading...</Text>}
</ScrollView>
);
};
export default InfiniteScrollView;
使用该封装组件时,你可以这样做:
<InfiniteScrollView
onReachBottom={() => fetchMoreData()}
onReachTop={() => fetchMoreDataAtTop()}
>
{/* Your scrollable content here */}
</InfiniteScrollView>
在这个例子中,当用户滑动到ScrollView
的底部时,会调用onReachBottom
回调,并在底部显示加载中的文本。当用户从顶部继续向下滑动时,会调用onReachTop
回调。这两个回调应该返回一个Promise,以便在数据加载完成后清除加载中的文本。
评论已关闭