美文网首页
react-native 使用ScrollView实现下拉刷新上

react-native 使用ScrollView实现下拉刷新上

作者: 物联白菜 | 来源:发表于2021-04-22 20:34 被阅读0次

参考来自:https://blog.csdn.net/qq_39197547/article/details/87702205

官方写法:

const Item = ({ item, index, onPress ,  onPress2}) => {
    return (
        <MyTouchableOpacity
            onPress={onPress}
            activeOpacity={1}
            style={{width:'100%',height:100,flexDirection:'row',paddingTop:10,paddingBottom:10,paddingHorizontal: 10}}>
            <View style={{flex:1,flexDirection:'row'}}>
                {
                    item.lesson_image_url===''?
                        <View style={{flex:1.7,backgroundColor:'#eee',borderRadius:3}}>
                            <Image source={require('../images/default_img.jpg')} style={{width:'100%',height:'100%'}}/>
                        </View>
                        :
                        <Image source={{uri:item.lesson_image_url}} style={{flex:1.7,borderRadius:3}}/>
                }

                <View style={{flex:2,justifyContent:'space-between',marginLeft:10}}>
                    <View>
                        <Text numberOfLines={1} style={{fontSize:14,lineHeight:26,color:'#0B0B34'}}>{item.lesson_title}</Text>
                        <Text numberOfLines={1} style={{lineHeight:24,fontSize:13,color:'#646464'}}>{item.lesson_general===''?'暂无介绍':item.lesson_general}</Text>
                    </View>
                    <View style={{flexDirection:'row',alignItems:'center'}}>
                        <Text style={{fontSize:13}} numberOflines={1}>{Util.toFixNum(item.virtual_num)}<Text style={{fontSize:10}}> 人看过</Text></Text>
                    </View>
                </View>
            </View>
        </MyTouchableOpacity>
    );
}


let page = 1

class YHomeIndex extends Component {
    constructor(props) {
        super(props);
        this.state = {
            refreshing:false,
            curIndex:0,
            LessonsArr:[],
        };
    }

    getLessonIndex(curIndex) {
        console.warn('page=====',page)
        try {
            let datakey = [];
                 datakey[xxxx] = xxxxx;
                datakey[xxxx] = xxxxx;
                datakey['page'] = page;
                datakey['size'] = 10;  //获取数量
                let url = URLconstant.LESSON_LIST
                Util.get(url, datakey, (datas)=>{
                    console.log('列表',datas)
                    let data = datas.data.list
                    if(datas.status===0){
                        if(page === 1){
                            this.setState({
                                LessonsArr:data
                            })
                        }else{
                            Array.prototype.push.apply(this.state.LessonsArr, data);
                        }
                    }
                }, this.errorcallback.bind(this));
        } catch (e) {
            console.warn('请求失败===',e)
        }
    }


    //listview上拉触发
    async onEndReached() {
        let {curIndex} = this.state
        page +=1
        this.getLessonIndex(curIndex); // 数据请求函数  
    }

    onRefresh = () => {
        console.log('正在刷新')
        let {curIndex} = this.state
        page = 1
        this.getLessonIndex(curIndex)

        setTimeout(()=>{
            this.setState({
                refreshing:false
            })
        },2000)
    }

    jumpToClassDetail(){
            this.props.navigation.push('Y_ClassDetail')
    }

    render(){
        const renderItem = ({ item,index,separators }) => (
                  <Item item={item} index={index} onPress={()=>this.jumpToClassDetail(item)}/>   // 列表里的事件传入
                );
          return(
                <View style={{flex:1}}>
                        <FlatList
                            showsVerticalScrollIndicator={false}
                            data={this.state.LessonsArr}
                            ListHeaderComponent={
                                    <View style={{flex:1}}>
                                        <View style={Styles.botContent}>
                                            <MyTab handleTabId={this.handleTabId.bind(this)} initTitleText={['人气TOP','新课']}/>
                                        </View>
                                    </View>
                            }
                            // numColumns={1}  //以多少列展示
                            renderItem={renderItem}
                            refreshControl={
                                <RefreshControl refreshing={this.state.refreshing} onRefresh={this.onRefresh} />
                            }
                            keyExtractor={item => String(item.id)}
                            onEndReached={this.onEndReached.bind(this)}
                            // ListFooterComponent={this.renderFooter.bind(this)}
                        />
          </View>
)}

export default YHomeIndex

// 按需

import React, {Component} from 'react';
import {
    Image,
    ScrollView,
    Text,
    TextInput,
    TouchableOpacity,
    View,
    StyleSheet,
    DeviceEventEmitter,
    ActivityIndicator,
    RefreshControl,
    StatusBar
} from "react-native";

let page = 1   //每次加载一页

export defaut class YHomeIndex extends Component {

    constructor(props) {
        super(props);
        // 初始状态
        this.state = {
            loaded: false,
            curIndex:0,
            LessonsArr:[],

        };
    }

//事件、方法
//下拉刷新
    _onRefresh =()=>{
        this.setState({
            isRefreshing: true,
        });
        console.log('正在刷新')
        let user_id = this.state.user_id;
        page = 1   //刷新时自动取page为1的数据
        this.getHomeIndex(user_id);  //某个请求
        this.getLessonIndex(user_id,page);; //某个请求

        setTimeout(()=>{
            //.concat拼接字符串,数组
            this.setState({
                isRefreshing: false,
            })
        }, 2000);
    }

    //判断滚动到底部--上拉加载
    handleScrollEnd = (event) => {
        // console.log(event)
        const contentHeight = event.nativeEvent.contentSize.height;
        const scrollViewHeight = event.nativeEvent.layoutMeasurement.height;
        const scrollOffset = event.nativeEvent.contentOffset.y;
        console.log(scrollOffset + scrollViewHeight,"444444444444",contentHeight);
        const isEndReached = scrollOffset + scrollViewHeight+45 >= contentHeight; // 是否滑动到底部
        const isContentFillPage = contentHeight >= scrollViewHeight; // 内容高度是否大于列表高度

        if (isContentFillPage && isEndReached) {
            page+=1   //累加page
           // if(page>5){
           //     page = 5    //只给加载到第五页
           //}
            console.log('可以加载更多了','第',page,'页')
             let user_id = this.state.user_id;
            this.getLessonIndex(user_id,page);    //这就是上拉加载的请求,通过page = 1、page = 2...达到请求不同页的数据,最后将不同页的数据concat合并一起,实现了上拉加载 , 加载图片和图标可以自己在ScrollView下面定义
        }
    };



//数据请求
    getLessonIndex(user_id,curIndex,page) {
        try {
            //LOG("登录成功的user_id=====" + user_id);
            let datakey = [];
            if (user_id != null || user_id != '') {
                datakey['user_id'] = user_id;
                datakey['page'] = page;
                // datakey['alreadyOwn'] = 1;  //获取拥有的
                // console.log('curIndex=====',curIndex)
                if(curIndex===0){
                    datakey['order'] = 1;  //获取排序
                }
                datakey['size'] = 10;  //获取数量

                let url = URLconstant.LESSON_LIST
                Util.get(url, datakey, (datas)=>{
                    console.warn('课程列表-首页===',datas)
                    let data = datas.data.list
                    for(let item of data){
                        if(item.teacher.length === 0){
                            item.teacher = {teacher_name:''}
                        }
                    }
                    console.warn('课程列表-首页===(转teacher字段)',data)

                    if(datas.status===0){
                        if(page===1){   //刷新自动请求第一页内容
                            this.setState({
                                LessonsArr:data,
                                loaded:false,
                            })
                        }else {
                            let LessonsArr = this.state.LessonsArr   // 这里就是加载合并各个page的内容
                            console.log('合并前===LessonsArr', LessonsArr,)
                            let newLessonsArr = LessonsArr.concat(data)
                            console.log('合并后的LessonsArr===', LessonsArr)

                            this.setState({
                                LessonsArr: newLessonsArr
                            })
                        }
                    }
                }, this.errorcallback.bind(this));

            }
        } catch (e) {
            console.warn('请求失败===',e)
        }
    }


    errorcallback(){
        console.warn('请求失败2====')
    }





//组件
<ScrollView
                  style={{flex: 1}}
                  showsVerticalScrollIndicator={false}

                   refreshControl={
                    <RefreshControl refreshing={this.state.isRefreshing}
                                                progressBackgroundColor={"#fff"}
                                                onRefresh={this._onRefresh}
                                                tintColor="#ff0000"
                                                title="Loading..."
                                                titleColor="#00ff00"
                                                colors={['#ccc', '#ccc', '#ccc']}
                                />
                            }
                            onScrollEndDrag={this.handleScrollEnd} //判断是否滚动到最底部
                        >


            <View>
                {
                    this.state.LessonsArr.map((item,id)=>{
                          return(
                                  XXXXXX
                                )
                      })
                }
</ScrollView>

//这里自定义加载icon
}

相关文章

网友评论

      本文标题:react-native 使用ScrollView实现下拉刷新上

      本文链接:https://www.haomeiwen.com/subject/wfbfrltx.html