之前使用的组件是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用起来方便的,而且提供的功能更多。
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持武林网。
新闻热点
疑难解答