续
1、安装
cnpm install @better-scroll/core --save
cnpm install @better-scroll/pull-up --save
cnpm install @better-scroll/pull-down --save
2、封装 BScroll.jsx
import React,{ useState, useEffect } from 'react';
import './BScroll.less';
import BScroll from '@better-scroll/core'
import Pullup from '@better-scroll/pull-up'
import PullDown from '@better-scroll/pull-down';
BScroll.use(Pullup)
BScroll.use(PullDown)
function BetterScroll (prop) {
// 获取传入的 方法
const { pullUp, pullDown } = prop
// 上拉加载
const fetchData = (bs) => {
pullUp(() => {
if (!bs) return
bs.finishPullUp()
bs.refresh()
})
}
// 上拉刷新
const fetchRefresh = (bs) => {
pullDown(() => {
if (!bs) return
bs.finishPullDown()
bs.refresh()
})
}
// 初始化bscroll
const [bScroll, setBScroll] = useState();
useEffect(() => {
// 初始化scroll
const bs = new BScroll('.wrapper', {
probeType: 3,
click: true,
pullUpLoad: true,
pullDownRefresh: true
})
console.log('首次');
// 首次进入获取数据
fetchRefresh(bs)
setBScroll(bs)
return () => {
// 组件卸载时记得将其销毁
setBScroll(null)
}
},[])
// 上拉加载
useEffect(() => {
if(!bScroll) return;
// 必须清除 一次事件,否则会累加 暂时未想到其他好办法
bScroll.off('pullingUp')
// 只执行一次,防止累加
bScroll.once('pullingUp', () => {
console.log('上拉')
fetchData(bScroll)
})
}, [prop])
// 下拉刷新
useEffect(() => {
if(!bScroll) return;
// 必须清除 一次事件,否则会累加 暂时未想到其他好办法
bScroll.off('pullingDown')
// 只执行一次,防止累加
bScroll.once('pullingDown', () => {
console.log('下拉')
fetchRefresh(bScroll)
})
}, [prop])
return (
<div className='wrapper'>
<div className='content'>
{
prop.children
}
</div>
</div>
)
}
export default BetterScroll;
3、BScroll.less
.wrapper {
overflow: hidden;
height: 100vh;
// .content {
// // 底部显示不全
// padding: 0 0 60px; /* no */
// }
}
4、使用 dent.jsx
import React, { useState } from 'react';
import './dent.less';
import { getPreAuthRecords } from 'apis';
import BScroll from 'src/base/BScroll/BScroll';
function dent () {
const [records, setRecords] = useState([]);
// 上拉
const pullUpLoad = (fn) => {
getPreAuthRecords()
.then(res => {
console.log(2);
const data = [...records, ...res.data]
setRecords(data)
fn()
})
}
// 下拉
const pullDownLoad = (fn) => {
getPreAuthRecords()
.then(res => {
console.log(1);
const data = [...res.data]
setRecords(data)
fn()
})
}
// 渲染
return (
<BScroll pullUp={pullUpLoad} pullDown={pullDownLoad}>
{
records.map( (item, i) => {
return <li className='listIten' key={item.ocId + i}>{`I am item ${i + 1} `}</li>
})
}
</BScroll>
)
}
export default dent;
5、dent.less
.content {
// 底部显示不全
padding: 0 0 60px; /* no */
}
.listIten {
font-size: @font-size-medium;
padding: 30px;
}
效果图