欢迎来到尧图网

客户服务 关于我们

您的位置:首页 > 新闻 > 焦点 > 詳細講一下RN(React Native)中的列表組件FlatList和SectionList

詳細講一下RN(React Native)中的列表組件FlatList和SectionList

2025/1/31 2:32:15 来源:https://blog.csdn.net/m0_73574455/article/details/145348154  浏览:    关键词:詳細講一下RN(React Native)中的列表組件FlatList和SectionList

1. FlatList 基礎使用

import React from 'react';
import { View, Text, FlatList, StyleSheet } from 'react-native';export const SimpleListDemo: React.FC = () => {// 1. 準備數據const data = [{ id: '1', title: '項目 1' },{ id: '2', title: '項目 2' },{ id: '3', title: '項目 3' },];// 2. 定義如何渲染每一項const renderItem = ({ item }) => (<View style={styles.item}><Text>{item.title}</Text></View>);// 3. 渲染 FlatListreturn (<FlatListdata={data}                    // 數據源renderItem={renderItem}        // 渲染項keyExtractor={item => item.id} // 指定 key/>);
};const styles = StyleSheet.create({item: {padding: 20,borderBottomWidth: 1,borderBottomColor: '#ccc',},
});

2. 添加頭部和底部

import React from 'react';
import { View, Text, FlatList, StyleSheet } from 'react-native';export const ListWithHeaderFooter: React.FC = () => {const data = [/* ... */];// 1. 定義頭部組件const ListHeader = () => (<View style={styles.header}><Text>這是列表頭部</Text></View>);// 2. 定義底部組件const ListFooter = () => (<View style={styles.footer}><Text>這是列表底部</Text></View>);return (<FlatListdata={data}renderItem={({ item }) => (<View style={styles.item}><Text>{item.title}</Text></View>)}ListHeaderComponent={ListHeader}   // 添加頭部ListFooterComponent={ListFooter}   // 添加底部keyExtractor={item => item.id}/>);
};const styles = StyleSheet.create({header: {padding: 15,backgroundColor: '#f0f0f0',},item: {padding: 20,borderBottomWidth: 1,borderBottomColor: '#ccc',},footer: {padding: 15,backgroundColor: '#f0f0f0',},
});

3. 下拉刷新和上拉加載

import React, { useState } from 'react';
import { View, Text, FlatList, RefreshControl, ActivityIndicator, StyleSheet 
} from 'react-native';export const RefreshLoadMoreList: React.FC = () => {const [refreshing, setRefreshing] = useState(false);const [loading, setLoading] = useState(false);const [data, setData] = useState([/* 初始數據 */]);// 1. 處理下拉刷新const onRefresh = async () => {setRefreshing(true);try {// 這裡請求新數據const newData = await fetchNewData();setData(newData);} finally {setRefreshing(false);}};// 2. 處理上拉加載更多const onLoadMore = async () => {if (loading) return;setLoading(true);try {// 這裡請求更多數據const moreData = await fetchMoreData();setData([...data, ...moreData]);} finally {setLoading(false);}};return (<FlatListdata={data}renderItem={({ item }) => (<View style={styles.item}><Text>{item.title}</Text></View>)}// 下拉刷新配置refreshControl={<RefreshControlrefreshing={refreshing}onRefresh={onRefresh}/>}// 上拉加載配置onEndReached={onLoadMore}onEndReachedThreshold={0.1}ListFooterComponent={loading ? <ActivityIndicator /> : null}/>);
};

4. 常用配置項說明

<FlatList// 基礎配置data={data}                          // 列表數據renderItem={renderItem}              // 渲染每一項的方法keyExtractor={item => item.id}       // 生成 key 的方法// 樣式相關contentContainerStyle={styles.list}  // 內容容器樣式style={styles.container}             // FlatList 本身樣式// 性能優化initialNumToRender={10}              // 首次渲染的項目數maxToRenderPerBatch={10}             // 每次渲染的最大數量windowSize={5}                       // 渲染窗口大小// 滾動相關showsVerticalScrollIndicator={false} // 是否顯示滾動條scrollEnabled={true}                 // 是否可以滾動
/>

5. 空列表處理

import React from 'react';
import { View, Text, FlatList, StyleSheet } from 'react-native';export const EmptyList: React.FC = () => {const data = [];  // 空數據const EmptyComponent = () => (<View style={styles.empty}><Text>暫無數據</Text></View>);return (<FlatListdata={data}renderItem={({ item }) => (/* ... */)}ListEmptyComponent={EmptyComponent}  // 當數據為空時顯示/>);
};const styles = StyleSheet.create({empty: {flex: 1,justifyContent: 'center',alignItems: 'center',padding: 20,},
});

2. SessionList基礎使用

import React from 'react';
import { View, Text, SectionList, StyleSheet } from 'react-native';export const SimpleSectionList: React.FC = () => {// 1. 準備分組數據const sections = [{title: '分組A',data: [{ id: '1', name: '項目A1' },{ id: '2', name: '項目A2' },]},{title: '分組B',data: [{ id: '3', name: '項目B1' },{ id: '4', name: '項目B2' },]}];// 2. 渲染每個項目const renderItem = ({ item }) => (<View style={styles.item}><Text>{item.name}</Text></View>);// 3. 渲染分組標題const renderSectionHeader = ({ section }) => (<View style={styles.header}><Text style={styles.headerText}>{section.title}</Text></View>);return (<SectionListsections={sections}                     // 分組數據renderItem={renderItem}                 // 渲染每個項目renderSectionHeader={renderSectionHeader} // 渲染分組標題keyExtractor={item => item.id}          // key提取器/>);
}const styles = StyleSheet.create({item: {padding: 15,backgroundColor: 'white',},header: {padding: 10,backgroundColor: '#f0f0f0',},headerText: {fontSize: 16,fontWeight: 'bold',},
});

2. 添加分組間距和分隔線

import React from 'react';
import { View, SectionList, StyleSheet } from 'react-native';export const SectionListWithSeparators: React.FC = () => {const sections = [/* ... */];// 1. 項目之間的分隔線const ItemSeparator = () => (<View style={styles.itemSeparator} />);// 2. 分組之間的間距const SectionSeparator = () => (<View style={styles.sectionSeparator} />);return (<SectionListsections={sections}renderItem={renderItem}renderSectionHeader={renderSectionHeader}ItemSeparatorComponent={ItemSeparator}     // 項目分隔線SectionSeparatorComponent={SectionSeparator} // 分組分隔線stickySectionHeadersEnabled={true}         // 分組標題固定/>);
};const styles = StyleSheet.create({itemSeparator: {height: 1,backgroundColor: '#eee',},sectionSeparator: {height: 10,backgroundColor: '#f5f5f5',},
});

3. 下拉刷新和加載更多

import React, { useState } from 'react';
import { SectionList, RefreshControl, ActivityIndicator 
} from 'react-native';export const RefreshableSectionList: React.FC = () => {const [refreshing, setRefreshing] = useState(false);const [loading, setLoading] = useState(false);const [sections, setSections] = useState([/* 初始數據 */]);// 1. 處理下拉刷新const onRefresh = async () => {setRefreshing(true);try {const newData = await fetchNewData();setSections(newData);} finally {setRefreshing(false);}};// 2. 處理加載更多const onLoadMore = async () => {if (loading) return;setLoading(true);try {const moreData = await fetchMoreData();setSections([...sections, ...moreData]);} finally {setLoading(false);}};return (<SectionListsections={sections}renderItem={renderItem}renderSectionHeader={renderSectionHeader}// 下拉刷新refreshControl={<RefreshControlrefreshing={refreshing}onRefresh={onRefresh}/>}// 加載更多onEndReached={onLoadMore}onEndReachedThreshold={0.2}ListFooterComponent={loading ? <ActivityIndicator /> : null}/>);
};

4.空列表和列表頭尾

import React from 'react';
import { View, Text, SectionList } from 'react-native';export const SectionListWithHeaderFooter: React.FC = () => {const sections = [/* ... */];// 1. 列表頭部const ListHeader = () => (<View style={styles.listHeader}><Text>列表頭部</Text></View>);// 2. 列表底部const ListFooter = () => (<View style={styles.listFooter}><Text>列表底部</Text></View>);// 3. 空列表顯示const ListEmpty = () => (<View style={styles.empty}><Text>暫無數據</Text></View>);return (<SectionListsections={sections}renderItem={renderItem}renderSectionHeader={renderSectionHeader}ListHeaderComponent={ListHeader}ListFooterComponent={ListFooter}ListEmptyComponent={ListEmpty}/>);
};

5. 常用配置項總結

<SectionList// 基礎配置sections={sections}                        // 分組數據renderItem={renderItem}                    // 渲染項目renderSectionHeader={renderSectionHeader}  // 渲染分組標題keyExtractor={(item) => item.id}          // key提取器// 分組相關stickySectionHeadersEnabled={true}        // 分組標題是否固定renderSectionFooter={renderSectionFooter}  // 渲染分組底部// 分隔線ItemSeparatorComponent={ItemSeparator}     // 項目分隔線SectionSeparatorComponent={SectionSeparator} // 分組分隔線// 性能優化initialNumToRender={10}                    // 初始渲染數量maxToRenderPerBatch={10}                   // 每批渲染數量windowSize={5}                             // 渲染窗口大小// 樣式相關contentContainerStyle={styles.container}   // 內容容器樣式style={styles.list}                        // 列表樣式
/>

版权声明:

本网仅为发布的内容提供存储空间,不对发表、转载的内容提供任何形式的保证。凡本网注明“来源:XXX网络”的作品,均转载自其它媒体,著作权归作者所有,商业转载请联系作者获得授权,非商业转载请注明出处。

我们尊重并感谢每一位作者,均已注明文章来源和作者。如因作品内容、版权或其它问题,请及时与我们联系,联系邮箱:809451989@qq.com,投稿邮箱:809451989@qq.com