ReactNative之FlatList的具體使用方法
之前使用的組件是ListView,當(dāng)時(shí)要添加一個(gè)下拉刷新,上拉加載的功能,所以對(duì)ListView做了一些封裝,但是后來看官方文檔,不建議再使用ListView,因?yàn)樾蕟栴},做過Android的朋友都知道,Android的ListView如果不自己處理一下,也是有效率問題的。所以官方又推出了FlatList,而且自帶上拉下拉的功能。
功能簡(jiǎn)介
- 完全跨平臺(tái)。
- 支持水平布局模式。
- 行組件顯示或隱藏時(shí)可配置回調(diào)事件。
- 支持單獨(dú)的頭部組件。
- 支持單獨(dú)的尾部組件。
- 支持自定義行間分隔線。
- 支持下拉刷新。
- 支持上拉加載。
- 支持跳轉(zhuǎn)到指定行(ScrollToIndex)。
如果需要分組/類/區(qū)(section),請(qǐng)使用SectionList(這個(gè)我們會(huì)在之后的文章中介紹)
使用
FlatList如果只做簡(jiǎn)單使用也是很簡(jiǎn)單的,這里我們會(huì)分難以程度,逐漸介紹:
直接使用
<FlatList
data={[{key: 'a'}, {key: 'b'}]}
renderItem={({item}) => <Text>{item.key}</Text>}
/>
可以看出跟之前的ListView很像,但是其中少了dataSource,這里,我們只需要傳遞數(shù)據(jù),其它的都交給FlatList處理好了。
屬性說明
- ItemSeparatorComponent行與行之間的分隔線組件。不會(huì)出現(xiàn)在第一行之前和最后一行之后。在這里可以根據(jù)需要插入一個(gè)view
- ListEmptyComponent列表為空時(shí)渲染該組件。可以是React Component, 也可以是一個(gè)render函數(shù), 或者渲染好的element。
- ListFooterComponent尾部組件
- ListHeaderComponent頭部組件
- columnWrapperStyle如果設(shè)置了多列布局(即將numColumns值設(shè)為大于1的整數(shù)),則可以額外指定此樣式作用在每行容器上。
- data為了簡(jiǎn)化起見,data屬性目前只支持普通數(shù)組。如果需要使用其他特殊數(shù)據(jù)結(jié)構(gòu),例如immutable數(shù)組,請(qǐng)直接使用更底層的VirtualizedList組件。
- extraData如果有除data以外的數(shù)據(jù)用在列表中(不論是用在renderItem還是Header或者Footer中),請(qǐng)?jiān)诖藢傩灾兄付?。同時(shí)此數(shù)據(jù)在修改時(shí)也需要先修改其引用地址(比如先復(fù)制到一個(gè)新的Object或者數(shù)組中),然后再修改其值,否則界面很可能不會(huì)刷新。
- getItem獲取每個(gè)Item
- getItemCount獲取Item屬相
- getItemLayout是一個(gè)可選的優(yōu)化,用于避免動(dòng)態(tài)測(cè)量?jī)?nèi)容尺寸的開銷,不過前提是你可以提前知道內(nèi)容的高度。如果你的行高是固定的getItemLayout用起來就既高效又簡(jiǎn)單,類似下面這樣:getItemLayout={(data, index) => ( {length: 行高, offset: 行高 * index, index} )}注意如果你指定了SeparatorComponent,請(qǐng)把分隔線的尺寸也考慮到offset的計(jì)算之中。
- horizontal設(shè)置為true則變?yōu)樗讲季帜J健?/li>
- initialNumToRender指定一開始渲染的元素?cái)?shù)量,最好剛剛夠填滿一個(gè)屏幕,這樣保證了用最短的時(shí)間給用戶呈現(xiàn)可見的內(nèi)容。注意這第一批次渲染的元素不會(huì)在滑動(dòng)過程中被卸載,這樣是為了保證用戶執(zhí)行返回頂部的操作時(shí),不需要重新渲染首批元素。
- initialScrollIndex指定渲染開始的item index
- keyExtractor此函數(shù)用于為給定的item生成一個(gè)不重復(fù)的key。Key的作用是使React能夠區(qū)分同類元素的不同個(gè)體,以便在刷新時(shí)能夠確定其變化的位置,減少重新渲染的開銷。若不指定此函數(shù),則默認(rèn)抽取item.key作為key值。若item.key也不存在,則使用數(shù)組下標(biāo)。
- legacyImplementation設(shè)置為true則使用舊的ListView的實(shí)現(xiàn)。
- numColumns多列布局只能在非水平模式下使用,即必須是horizontal={false}。此時(shí)組件內(nèi)元素會(huì)從左到右從上到下按Z字形排列,類似啟用了flexWrap的布局。組件內(nèi)元素必須是等高的——暫時(shí)還無法支持瀑布流布局。
- onEndReached當(dāng)列表被滾動(dòng)到距離內(nèi)容最底部不足onEndReachedThreshold的距離時(shí)調(diào)用。
- onEndReachedThreshold決定當(dāng)距離內(nèi)容最底部還有多遠(yuǎn)時(shí)觸發(fā)onEndReached回調(diào)。注意此參數(shù)是一個(gè)比值而非像素單位。比如,0.5表示距離內(nèi)容最底部的距離為當(dāng)前列表可見長(zhǎng)度的一半時(shí)觸發(fā)。
- onRefresh如果設(shè)置了此選項(xiàng),則會(huì)在列表頭部添加一個(gè)標(biāo)準(zhǔn)的RefreshControl控件,以便實(shí)現(xiàn)“下拉刷新”的功能。同時(shí)你需要正確設(shè)置refreshing屬性。
- onViewableItemsChanged在可見行元素變化時(shí)調(diào)用??梢姺秶妥兓l率等參數(shù)的配置請(qǐng)?jiān)O(shè)置viewabilityconfig屬性
- refreshing在等待加載新數(shù)據(jù)時(shí)將此屬性設(shè)為true,列表就會(huì)顯示出一個(gè)正在加載的符號(hào)。
- renderItem根據(jù)行數(shù)據(jù)data,渲染每一行的組件。這個(gè)參照下面的demo
- viewabilityConfig請(qǐng)參考ViewabilityHelper 的源碼來了解具體的配置。
方法
scrollToEnd
滾動(dòng)到底部。如果不設(shè)置getItemLayout
屬性的話,可能會(huì)比較卡。
scrollToIndex
滾動(dòng)到指定index的item
如果不設(shè)置getItemLayout
屬性的話,無法跳轉(zhuǎn)到當(dāng)前可視區(qū)域以外的位置。
scrollToItem
滾動(dòng)到指定item,如果不設(shè)置getItemLayout
屬性的話,可能會(huì)比較卡。
scrollToOffset
滾動(dòng)指定距離
Demo:
import React, {Component} from 'react';
import {
StyleSheet,
View,
FlatList,
Text,
Button,
} from 'react-native';
var ITEM_HEIGHT = 100;
export default class FlatListDemo extends Component {
_flatList;
_renderItem = (item) => {
var txt = '第' + item.index + '個(gè)' + ' title=' + item.item.title;
var bgColor = item.index % 2 == 0 ? 'red' : 'blue';
return <Text style={[{flex:1,height:ITEM_HEIGHT,backgroundColor:bgColor},styles.txt]}>{txt}</Text>
}
_header = () => {
return <Text style={[styles.txt,{backgroundColor:'black'}]}>這是頭部</Text>;
}
_footer = () => {
return <Text style={[styles.txt,{backgroundColor:'black'}]}>這是尾部</Text>;
}
_separator = () => {
return <View style={{height:2,backgroundColor:'yellow'}}/>;
}
render() {
var data = [];
for (var i = 0; i < 100; i++) {
data.push({key: i, title: i + ''});
}
return (
<View style={{flex:1}}>
<Button title='滾動(dòng)到指定位置' onPress={()=>{
//this._flatList.scrollToEnd();
//this._flatList.scrollToIndex({viewPosition:0,index:8});
this._flatList.scrollToOffset({animated: true, offset: 2000});
}}/>
<View style={{flex:1}}>
<FlatList
ref={(flatList)=>this._flatList = flatList}
ListHeaderComponent={this._header}
ListFooterComponent={this._footer}
ItemSeparatorComponent={this._separator}
renderItem={this._renderItem}
//numColumns ={3}
//columnWrapperStyle={{borderWidth:2,borderColor:'black',paddingLeft:20}}
//horizontal={true}
//getItemLayout={(data,index)=>(
//{length: ITEM_HEIGHT, offset: (ITEM_HEIGHT+2) * index, index}
//)}
//onEndReachedThreshold={5}
//onEndReached={(info)=>{
//console.warn(info.distanceFromEnd);
//}}
//onViewableItemsChanged={(info)=>{
//console.warn(info);
//}}
data={data}>
</FlatList>
</View>
</View>
);
}
}
const styles = StyleSheet.create({
txt: {
textAlign: 'center',
textAlignVertical: 'center',
color: 'white',
fontSize: 30,
}
});
效果圖:

進(jìn)階使用
在這里我準(zhǔn)備了一份代碼示例:
const {width,height}=Dimensions.get('window')
export default class Main extends Component{
// 構(gòu)造
constructor(props) {
super(props);
}
refreshing(){
let timer = setTimeout(()=>{
clearTimeout(timer)
alert('刷新成功')
},1500)
}
_onload(){
let timer = setTimeout(()=>{
clearTimeout(timer)
alert('加載成功')
},1500)
}
render() {
var data = [];
for (var i = 0; i < 100; i++) {
data.push({key: i, title: i + ''});
}
return (
<View style={{flex:1}}>
<Button title='滾動(dòng)到指定位置' onPress={()=>{
this._flatList.scrollToOffset({animated: true, offset: 2000});
}}/>
<View style={{flex:1}}>
<FlatList
ref={(flatList)=>this._flatList = flatList}
ListHeaderComponent={this._header}
ListFooterComponent={this._footer}
ItemSeparatorComponent={this._separator}
renderItem={this._renderItem}
onRefresh={this.refreshing}
refreshing={false}
onEndReachedThreshold={0}
onEndReached={
this._onload
}
numColumns ={3}
columnWrapperStyle={{borderWidth:2,borderColor:'black',paddingLeft:20}}
//horizontal={true}
getItemLayout={(data,index)=>(
{length: 100, offset: (100+2) * index, index}
)}
data={data}>
</FlatList>
</View>
</View>
);
}
_renderItem = (item) => {
var txt = '第' + item.index + '個(gè)' + ' title=' + item.item.title;
var bgColor = item.index % 2 == 0 ? 'red' : 'blue';
return <Text style={[{flex:1,height:100,backgroundColor:bgColor},styles.txt]}>{txt}</Text>
}
_header = () => {
return <Text style={[styles.txt,{backgroundColor:'black'}]}>這是頭部</Text>;
}
_footer = () => {
return <Text style={[styles.txt,{backgroundColor:'black'}]}>這是尾部</Text>;
}
_separator = () => {
return <View style={{height:2,backgroundColor:'yellow'}}/>;
}
}
const styles=StyleSheet.create({
container:{
},
content:{
width:width,
height:height,
backgroundColor:'yellow',
justifyContent:'center',
alignItems:'center'
},
cell:{
height:100,
backgroundColor:'purple',
alignItems:'center',
justifyContent:'center',
borderBottomColor:'#ececec',
borderBottomWidth:1
},
txt: {
textAlign: 'center',
textAlignVertical: 'center',
color: 'white',
fontSize: 30,
}
})
運(yùn)行效果如下:

總結(jié)
總體來說Flatlist還是比ListView用起來方便的,而且提供的功能更多。
以上就是本文的全部?jī)?nèi)容,希望對(duì)大家的學(xué)習(xí)有所幫助,也希望大家多多支持腳本之家。
相關(guān)文章
React實(shí)現(xiàn)一個(gè)倒計(jì)時(shí)hook組件實(shí)戰(zhàn)示例
這篇文章主要為大家介紹了React實(shí)現(xiàn)一個(gè)倒計(jì)時(shí)hook組件,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進(jìn)步,早日升職加薪2023-02-02
詳解React如何使用??useReducer???高階鉤子來管理狀態(tài)
useReducer是React中的一個(gè)鉤子,用于替代?useState來管理復(fù)雜的狀態(tài)邏輯,本文將詳細(xì)介紹如何在React中使用?useReducer高階鉤子來管理狀態(tài),感興趣的可以了解下2025-02-02
useReducer使用詳解及其應(yīng)用場(chǎng)景
這篇文章主要介紹了useReducer使用詳解及其應(yīng)用場(chǎng)景,具有很好的參考價(jià)值,希望對(duì)大家有所幫助,如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2024-03-03
ReactNative中使用Redux架構(gòu)總結(jié)
本篇文章主要介紹了ReactNative中使用Redux架構(gòu)總結(jié),小編覺得挺不錯(cuò)的,現(xiàn)在分享給大家,也給大家做個(gè)參考。一起跟隨小編過來看看吧2017-12-12
react?實(shí)現(xiàn)表格列表拖拽排序的示例
本文主要介紹了react?實(shí)現(xiàn)表格列表拖拽排序,文中通過示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2023-02-02

