React-Native应用ListView实现上拉下拉刷新效果实践
发布时间:2020-12-15 07:36:53 所属栏目:百科 来源:网络整理
导读:前言 在移动应用中,上拉刷新加载更多,下拉刷新列表的操作非常常见,那么在React-Native中应该如何实现呢,我们具体来看一下? 必备的组件 ListView :效果和ScrollView比较类似,但是效率会高些,因为只渲染当前屏幕显示的数据。 RefreshControl :这是一
前言在移动应用中,上拉刷新加载更多,下拉刷新列表的操作非常常见,那么在React-Native中应该如何实现呢,我们具体来看一下? 必备的组件
上面两个组件都是RN自带的组件的实现起来比较容易。 实现方法对于上拉刷新我们需要引入ActivityIndicator,这是最近几个版本才有的组件,之前叫做ActivityIndicatorIOS. 目前可以支持Android和IOS两个系统。 引入组件: import {
ListView,
RefreshControl,ActivityIndicator
} from 'react-native';
具体代码: reloadWordData() {
return new Promise((resolve) => { setTimeout(()=>{resolve()},2000) }); } renderFooter() { return <ActivityIndicator />; } render() { return ( <View style={GeneralStyle.container}> <Spinner visible={this.state.visible} textStyle={{color: '#FFF'}} /> <ListView refreshControl={ <RefreshControl refreshing={false} onRefresh={this.reloadWordData.bind(this)} />} dataSource={this.state.dataSource} renderRow={this.renderRow} renderFooter={this.renderFooter} /> </View> ); }
对于下拉操作我们只要嵌入RefreshControl即可,即定义个prop,并且定义一个刷新触发的方法,和控制是否刷新的状态。 refreshControl={
<RefreshControl
refreshing={false}
onRefresh={this.reloadWordData.bind(this)}
/>}
对于上拉,需要变相处理,生成一个footer,ListView中存在一个 renderFooter() { if(this.state&&this.state.isShowBottomRefresh){ return (<View style={{marginVertical: 10}}> <ActivityIndicator /> </View>); } return <View style={{marginVertical: 10}} />;; }
当页面滚动底部是会自动触发onEndReached方法,这里存在一个问题,就是在这个方法中执行setState的时候,onEndReach会因此被触发两次,所以需要判断一下,在官方demo中同样存在这个代码。 onEndReached() {
if(this.isFirstTime){
if(!this.state.isShowBottomRefresh){
this.isFirstTime = false;
}
return;
}
this.isFirstTime = true;
this.setState({isShowBottomRefresh: true});
setTimeout(()=>{ this.isFirstTime = true; this.setState({ isShowBottomRefresh: false }); },4000); }
效果图(编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |