react-native 给ScrollView添加上拉加载和下拉刷新
目录
- 上拉加载
- 下拉刷新
上拉加载
添加onScrollEndDrag事件
<ScrollViewonScrollEndDrag={this.onMomentumScrollEnd}>...</ScrollView>
onScrollEndDrag事件方法
- 属性值计算,
offSetY + oriageScrollHeight >= contentSizeHeight - 1可判断下拉到底部- 我加了
pageLoadingFull属性判断是否加载全部数据,pageLoading用于节流防止加载过程中又触发加载。
onMomentumScrollEnd = (event) => {const offSetY = event.nativeEvent.contentOffset.y; // 获取滑动的距离const contentSizeHeight = event.nativeEvent.contentSize.height; // scrollView contentSize 高度const oriageScrollHeight = event.nativeEvent.layoutMeasurement.height; // scrollView高度const { pageLoadingFull, pageLoading } = this.state;console.log(`offSetY${offSetY}`);console.log(`oriageScrollHeight${oriageScrollHeight}`);console.log(`contentSizeHeight${contentSizeHeight}`);if (offSetY + oriageScrollHeight >= contentSizeHeight - 1) {if (!pageLoadingFull && !pageLoading) {this.loadMore();}}};
加载内容
loadMore = async () => {//开始加载设置加载中进行节流this.setState({ pageLoading: true });const json = await ...//异步加载数据if(...){//数据若是加载后加载全部,则设置已经加载全部this.setState({ pageLoadingFull: true });}//加载结束this.setState({ pageLoading: false });};
底部提示
import { TouchableOpacity, ActivityIndicator } from 'react-native';<Viewstyle={{// backgroundColor: 'blue',height: 40,zIndex: 10,justifyContent: 'center',}}>{pageLoadingFull ? (<Text style={{ textAlign: 'center' }}>没有更多了</Text>) : pageLoading ? (<ActivityIndicator size='large' />) : (<TouchableOpacityonPress={() => {this.loadMore();}}><Text style={{ textAlign: 'center' }}>更多...</Text></TouchableOpacity>)}</View>
下拉刷新
<ScrollView// data={['']}// renderItem={this.renderPage}// onScroll={(e) => { console.log(e.target); }}refreshControl={<RefreshControlrefreshing={this.state.refreshing}onRefresh={() => {this.setState({refreshing: true,pageLoadingFull: false,});this._load();}}tintColor='black'title={this.state.refreshing ? '刷新中' : '下拉刷新'}titleColor='black'colors={['white', 'gray', 'black']}progressBackgroundColor='lightblue'/>}>...</ScrollView>
本文来自互联网用户投稿,文章观点仅代表作者本人,不代表本站立场,不承担相关法律责任。如若转载,请注明出处。 如若内容造成侵权/违法违规/事实不符,请点击【内容举报】进行投诉反馈!
