使用ScrollView实现
import React, { useState, useCallback } from 'react';
import { ScrollView, ActivityIndicator, View, Text, StyleSheet } from 'react-native';
const LoadMoreScrollView = () => {
const [loading, setLoading] = useState(false);
const [data, setData] = useState(Array.from({ length: 20 }, (_, index) => index));
const handleLoadMore = useCallback(() => {
setLoading(true);
setTimeout(() => {
setData((prevData) => [
...prevData,
...Array.from({ length: 20 }, (_, index) => index + prevData.length),
]);
setLoading(false);
}, 2000);
}, []);
const handleScroll = ({ nativeEvent }) => {
if (nativeEvent.contentOffset.y >= nativeEvent.contentSize.height - nativeEvent.layoutMeasurement.height) {
if (!loading) {
handleLoadMore();
}
}
};
return (
<ScrollView
// 添加滚动事件监听
onScroll={handleScroll}
// 设置滚动事件节流,优化性能
scrollEventThrottle={16}
// 设置样式
style={styles.container}
>
{data.map((item, index) => (
// 渲染每个列表项
<View key={index} style={styles.item}>
<Text>{item}</Text>
</View>
))}
{/* 如果正在加载,则显示加载指示器 */}
{loading && (
<ActivityIndicator size="large" style={styles.loader} />
)}
</ScrollView>
);
};
const styles = StyleSheet.create({
container: {
flex: 1,
},
item: {
height: 100,
justifyContent: 'center',
alignItems: 'center',
borderBottomWidth: 1,
borderBottomColor: '#ccc',
},
loader: {
marginVertical: 20,
},
});
export default LoadMoreScrollView;
使用FlatList实现
import React, { useState, useEffect } from 'react';
import { FlatList, View, Text, ActivityIndicator, StyleSheet } from 'react-native';
const MyComponent = () => {
const [data, setData] = useState([]);
const [loading, setLoading] = useState(false);
const [page, setPage] = useState(1);
const fetchData = () => {
setLoading(true);
setTimeout(() => {
const newData = Array.from({ length: 10 }, (_, index) => ({ id: index + 1, text: `Item ${index + 1}` }));
setData([...data, ...newData]);
setLoading(false);
}, 1000);
};
const handleLoadMore = () => {
if (!loading) {
setPage(page + 1);
fetchData();
}
};
useEffect(() => {
fetchData();
}, []);
const renderFooter = () => {
return loading ? (
<View style={styles.footer}>
<ActivityIndicator size="large" color="blue" />
</View>
) : null;
};
return (
<FlatList
data={data}
renderItem={({ item }) => (
<View style={styles.item}>
<Text>{item.text}</Text>
</View>
)}
keyExtractor={(item) => item.id.toString()}
onEndReached={handleLoadMore}
onEndReachedThreshold={0.1}
ListFooterComponent={renderFooter}
/>
);
};
const styles = StyleSheet.create({
item: {
padding: 20,
borderBottomWidth: 1,
borderBottomColor: '#ccc',
},
footer: {
alignItems: 'center',
justifyContent: 'center',
paddingVertical: 20,
},
});
export default MyComponent;