FlatList and SectionList
Scorri per mostrare il menu
When you need to display lists of data in your React Native app, you will often use either FlatList or SectionList. These two components are designed for efficiently rendering large or complex lists, handling scrolling, and optimizing memory usage by rendering only visible items.
FlatList is best for showing long, flat arrays of data—like a list of messages, products, or contacts. It only renders the items that are visible on the screen, making it much more efficient than manually mapping over arrays in a ScrollView. If your data is grouped (such as messages by date or contacts by first letter), SectionList is a better choice. SectionList lets you render grouped data with section headers and manages both the groups and the items inside each group.
To see how FlatList works, look at this example where you render a list of fruit names. You provide the data as an array and define how each item should look using the renderItem prop. Each item should also have a unique key, which you can specify using the keyExtractor prop.
Here is a simple FlatList in action:
import React from 'react';
import { FlatList, Text, View } from 'react-native';
const fruits = [
{ id: '1', name: 'Apple' },
{ id: '2', name: 'Banana' },
{ id: '3', name: 'Cherry' },
{ id: '4', name: 'Date' },
{ id: '5', name: 'Elderberry' }
];
export default function FruitList() {
return (
<FlatList
data={fruits}
keyExtractor={item => item.id}
renderItem={({ item }) => (
<View style={{ padding: 16, borderBottomWidth: 1, borderColor: '#ccc' }}>
<Text style={{ fontSize: 18 }}>{item.name}</Text>
</View>
)}
/>
);
}
In this code, the FlatList takes the fruits array as its data prop. The keyExtractor ensures each item has a unique key, which is important for performance. The renderItem function describes how each fruit should be displayed, wrapping the fruit name in a styled View and Text.
This approach is much more efficient than rendering all items at once, especially for long lists. FlatList manages scrolling and only loads the items currently visible on the screen, which keeps your app fast and responsive.
Grazie per i tuoi commenti!
Chieda ad AI
Chieda ad AI
Chieda pure quello che desidera o provi una delle domande suggerite per iniziare la nostra conversazione