之前使用的組件是ListView,當時要添加一個下拉刷新,上拉加載的功能,所以對ListView做了一些封裝,但是后來看官方文檔,不建議再使用ListView,因為效率問題,做過Android的朋友都知道,Android的ListView如果不自己處理一下,也是有效率問題的。所以官方又推出了FlatList,而且自帶上拉下拉的功能。
功能簡介
如果需要分組/類/區(section),請使用SectionList(這個我們會在之后的文章中介紹)
使用
FlatList如果只做簡單使用也是很簡單的,這里我們會分難以程度,逐漸介紹:
直接使用
<FlatListdata={[{key: 'a'}, {key: 'b'}]}renderItem={({item}) => <Text>{item.key}</Text>}/>可以看出跟之前的ListView很像,但是其中少了dataSource,這里,我們只需要傳遞數據,其它的都交給FlatList處理好了。
屬性說明
方法
scrollToEnd
滾動到底部。如果不設置getItemLayout
屬性的話,可能會比較卡。
scrollToIndex
滾動到指定index的item
如果不設置getItemLayout
屬性的話,無法跳轉到當前可視區域以外的位置。
scrollToItem
滾動到指定item,如果不設置getItemLayout
屬性的話,可能會比較卡。
scrollToOffset
滾動指定距離
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 + '個' + ' 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='滾動到指定位置' 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,  }});效果圖:

進階使用
在這里我準備了一份代碼示例:
const {width,height}=Dimensions.get('window')export default class Main extends Component{  // 構造  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='滾動到指定位置' 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 + '個' + ' 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,  }})運行效果如下:

總結
總體來說Flatlist還是比ListView用起來方便的,而且提供的功能更多。
以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支持武林網。
新聞熱點
疑難解答