react组件,进行页面的下拉加载。包括type=0“加载更多。”,type=1“正在加载中。。。”,type=2“没有更多数据” 。
父 组件引用代码如下
import AppPullRefresh from '@/component/pull-refresh'
const {pageSize, pageData, type} = this.state
<AppPullRefresh
className='reimbursed-list-wrap' // 外部添加className加以区分
onPullRefresh={this.handlePullRefresh} //触发加载ajax的function
type={type} // 传送加载组件的状态
count={pageData.length} // 数据当前的总数量
pageSize={pageSize} //
>
{pageData.map((item, index) => {
return (
<div key={index}>
// 渲染list的数据
{item.value}
</div>
)
})}
</AppPullRefresh>
子组件代码部分如下
import React, { Component } from 'react';
import T from 'prop-types';
import _ from 'lodash'
import './index.less'
class PullRefresh extends Component {
handleScroll = () => {
if (this.props.count < this.props.pageSize) return
if (this.props.type === 1 || this.props.type === 2) return
const wrap = this.refs['pull-refresh']
const currentScroll = wrap.scrollTop + wrap.clientHeight
// 触底
if (currentScroll >= (wrap.scrollHeight - 10)) {
this.loadData()
}
}
handleLoadClick = () => {
this.loadData()
}
loadData = () => {
this.props.onPullRefresh()
}
renderLoading () {
switch (this.props.type) {
case 0: // 加载更多
return <div className='jz-pull-refresh-load-more' onClick={this.handleLoadClick}>显示更多</div>
case 1: // 加载中
return (
<div className='jz-pull-refresh-loading-wrap'>
<div className='jz-pull-refresh-loading-icon' />
<div className='jz-pull-refresh-loading-label'>加载中...</div>
</div>
)
case 2: // 无样式
// return null
return <div className='jz-pull-refresh-no-more'>没有更多了</div>
}
}
render () {
return (
<div
className={`jz-pull-refresh-wrap ${this.props.className}`}
ref='pull-refresh'
onTouchMove={_.throttle(this.handleScroll, 200, {
leading: false,
trailing: true,
})}
// onScroll={_.throttle(this.handleScroll, 200, {
// leading: false,
// trailing: true,
// })}
>
<div className='jz-pull-refresh-list-wrap'>
{this.props.children}
</div>
{/* 大于分页数据才显示loading */}
{this.props.count >= this.props.pageSize ? (
<div className='jz-pull-refresh-loading-type-wrap'>
{this.renderLoading()}
</div>
) : null}
</div>
)
}
}
PullRefresh.propTypes = {
className: T.string,
children: T.any,
onPullRefresh: T.func.isRequired,
type: T.oneOf([0, 1, 2]),
count: T.number.isRequired,
pageSize: T.number.isRequired,
}
export default PullRefresh