js
复制代码
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);
// 模拟从API获取数据
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;