關於antd-mobile中列表上拉加載PullToRefresh的使用


相信有很多小伙伴發現antd-mobile中的下拉刷新組件,也發現例子挺難的,其實這個組件並沒有那么復雜,只是demo例子不好理解,給大家提供一個簡單的demo,或許可以幫到你

上拉刷新下拉加載

- 因為它用react-dom做操作了,所以把react-dom也導進來
- rowID是每次的ID,rowData是每次的數據
- renderSseprator就是個分隔符
- this.state.dataSource就是數據源 
- 外圍的那個const的dataSource是一種數據結構,它有一個方法叫cloneWithRows
- Button沒用,刪就完了
- renderFooter是為了做上拉刷新時的Loading效果
- 第一步是通過dataSource去拿數據,第二步是通過render(row)去渲染那個模板
- rowData是每一頁的數據,就是每次裝載進來的數據,rowID是它幫你封裝好的,直接在key={rowID}用就行,
在DidMount整完數據以后在這邊的rouData就是你的state.dataSource里面的數據(第一頁)
- renderSeparator 就是剛開始他們行和行之間的分隔符
- pageSize是刷新的時候一次顯示幾條數據

附上代碼,可直接復制過去,根據你的需求更改

import React,{ Component } from 'react'
import ReactDOM from 'react-dom'    //下拉刷新組件依賴react-dom,所以需要將其引進來

import { PullToRefresh, ListView } from 'antd-mobile';

class ListContainer extends Component {
  constructor(props) {
    super(props);
    const dataSource = new ListView.DataSource({  //這個dataSource有cloneWithRows方法
      rowHasChanged: (row1, row2) => row1 !== row2,
    });   
    
    this.pageNo = 0 //定義分頁信息
    this.state = {
      dataSource,
      refreshing: true,
      isLoading: true,
      height: document.documentElement.clientHeight,
      useBodyScroll: false,
      hasMore: true
    };
  }

  componentDidUpdate() {
    if (this.state.useBodyScroll) {
      document.body.style.overflow = 'auto';
    } else {
      document.body.style.overflow = 'hidden';
    }
  }

  async componentDidMount() {
    const hei = this.state.height - ReactDOM.findDOMNode(this.lv).offsetTop;

    this.rData = (await this.genData()).sceneryinfo;
    console.log(this.rData)
    this.setState({
      dataSource: this.state.dataSource.cloneWithRows(this.rData),
      height: hei,
      refreshing: false,
      isLoading: false,
    });
  }
  genData(){  //請求數據的方法
    this.pageNo++     //每次下拉的時候pageNo++                                                                                 
    return fetch('/scenery/json/scenerynearycitylist.html?CountryId=0&ProvinceId=3&CityId=53&LbTypes=&sorttype=0&page='+this.pageNo+'&gradeid=0&themeid=0&pricerange=0&issearchbytimenow=0&paytype=0&range=0&keyword=0&IsGlobal=0&IsYiYuan=0&cityArea=0&lat=0&lon=0', 
            {
              method: 'GET',
              headers: {
                  'content-type': 'application/json'
              },
            })
            .then(response => response.json())
            .then(function(result) {
                if(result){
                  return result
                }else{
                  this.setState({
                    hasMore: false
                  })
                }
            })
  }

  onRefresh = () => {
    // this.setState({ refreshing: true, isLoading: true });
    // // simulate initial Ajax
    // setTimeout(() => {
    //   this.rData = genData();
    //   this.setState({
    //     dataSource: this.state.dataSource.cloneWithRows(this.rData),
    //     refreshing: false,
    //     isLoading: false,
    //   });
    // }, 600);
  };

  onEndReached = async (event) => {
    // load new data
    // hasMore: from backend data, indicates whether it is the last page, here is false
    if (this.state.isLoading && !this.state.hasMore) {
      return;
    }   //如果this.state.hasMore為false,說明沒數據了,直接返回
    console.log('reach end', event);
    this.setState({ isLoading: true });
    this.rData = [...this.rData, ...((await this.genData()).sceneryinfo)];  //每次下拉之后將新數據裝填過來
    this.setState({
      dataSource: this.state.dataSource.cloneWithRows(this.rData),
      isLoading: false,
    });
  };

  render() {
    //這里就是個渲染數據,rowData就是每次過來的那一批數據,已經自動給你遍歷好了,rouID可以作為key值使用,直接渲染數據即可
    const row = (rowData, sectionID, rowID) => {
      return (
        <div key={rowID} style={{"height":"100px"}}>{rowData.name}</div>
      );
    };
    return (
      <div>
        <ListView
          key={this.state.useBodyScroll ? '0' : '1'}
          ref={el => this.lv = el}
          dataSource={this.state.dataSource}
          renderFooter={    //renderFooter就是下拉時候的loading效果,這里的內容可以自己隨需求更改
            () => (
                  <div style={{ padding: 30, textAlign: 'center' }}>
                    {this.state.isLoading ? 'Loading...' : 'Loaded'}
                  </div>
                )
          }
          renderRow={row}   //渲染你上邊寫好的那個row
          useBodyScroll={this.state.useBodyScroll}
          style={this.state.useBodyScroll ? {} : {
            height: this.state.height,
            border: '1px solid #ddd',
            margin: '5px 0',
          }}
          pullToRefresh={<PullToRefresh
            refreshing={this.state.refreshing}
            onRefresh={this.onRefresh}
          />}
          onEndReached={this.onEndReached}
          pageSize={8}    //每次下拉之后顯示的數據條數
        />
      </div>
    );
  }
}

export default ListContainer

如果說你看到了這里,是不是覺得還是有點東西的,如果你覺得幫到你了,給個評論鼓勵鼓勵孩子吧,發了這么多到現在就一條評論,挺可憐的。后續給大家發一個在下拉刷新組件中如何使用redux,感謝查閱~.~


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM