在移动端开发中列表页是非常常见的页面,在React Native中我们一般使用FlatList或SectionList组件实现这些列表视图。通常列表页都会有大量的数据需要加载显示,这时候就用到了分页加载,因此对于列表组件来说,实现下拉刷新和上拉加载在很多情况下是必不可少的。
本篇文章基于FlatList封装一个支持下拉刷新和上拉加载的RefreshListView,对原始的FlatList进行封装之后,再调用上拉和下拉刷新就十分方便了。
下拉刷新的实现十分简单,这里我们沿用FlatList本身的属性来实现
onRefresh— 设置此选项后,则会在列表头部添加一个标准的RefreshControl控件,以便实现“下拉刷新”的功能。同时你需要正确设置refreshing属性。
refreshing—— bool值,用来控制刷新控件的显示与隐藏。刷新完成后设为false。
通过这两个属性设置我们就可以实现FlatList头部的刷新操作,控件使用默认的样式,Android和iOS沿用各自系统的组件来显示。
重点在于上拉加载更多,React Native的列表组件中没有这个功能,需要我们自己实现。 对于上拉加载,通常我们有几种状态,这里我创建一个RefreshState.js文件存放上拉加载的状态:
export default { Idle: 'Idle', // 初始状态,无刷新的情况 CanLoadMore: 'CanLoadMore', // 可以加载更多,表示列表还有数据可以继续加载 Refreshing: 'Refreshing', // 正在刷新中 NoMoreData: 'NoMoreData', // 没有更多数据了 Failure: 'Failure' // 刷新失败}
然后根据这几种状态来封装一个RefreshFooter组件,使其根据不同状态显示不同内容,废话不多说上代码:
import React, {Component} from 'react';import {View, Text, ActivityIndicator, StyleSheet, TouchableOpacity} from 'react-native';import RefreshState from './RefreshState';import PropTypes from 'prop-types';export default class RefreshFooter extends Component { static propTypes = { onLoadMore: PropTypes.func, // 加载更多数据的方法 onRetryLoading: PropTypes.func, // 重新加载的方法 }; static defaultProps = { footerRefreshingText: "努力加载中", footerLoadMoreText: "上拉加载更多", footerFailureText: "点击重新加载", footerNoMoreDataText: "已全部加载完毕" }; render() { let {state} = this.props; let footer = null; switch (state) { case RefreshState.Idle: // Idle情况下为null,不显示尾部组件 break; case RefreshState.Refreshing: // 显示一个loading视图 footer = <View style={styles.loadingView}> <ActivityIndicator size="small"/> <Text style={styles.refreshingText}>{this.props.footerRefreshingText}</Text> </View>; break; case RefreshState.CanLoadMore: // 显示上拉加载更多的文字 footer = <View style={styles.loadingView}> <Text style={styles.footerText}>{this.props.footerLoadMoreText}</Text> </View>; break; case RefreshState.NoMoreData: // 显示没有更多数据的文字,内容可以自己修改 footer = <View style={styles.loadingView}> <Text style={styles.footerText}>{this.props.footerNoMoreDataText}</Text> </View>; break; case RefreshState.Failure: // 加载失败的情况使用TouchableOpacity做一个可点击的组件,外部调用onRetryLoading重新加载数据 footer = <TouchableOpacity style={styles.loadingView} onPress={()=>{ this.props.onRetryLoading && this.props.onRetryLoading(); }}> <Text style={styles.footerText}>{this.props.footerFailureText}</Text> </TouchableOpacity>; break; } return footer; }}const styles = StyleSheet.create({ loadingView: { flexDirection: 'row', justifyContent: 'center', alignItems: 'center', padding: 15, }, refreshingText: { fontSize: 12, color: "#666666", paddingLeft: 10, }, footerText: { fontSize: 12, color: "#666666" }});
新闻热点
疑难解答
图片精选