下拉刷新
首先,在页面顶部添加一个下拉刷新的区域,然后监听touchstart、touchmove和touchend等事件、当用户在下拉刷新区域进行下拉操作时,触发touchmove事件,并判断下拉的距离是否超过一定阈值。如果超过阈值,则触发下拉刷新操作,更新数据并重新渲染页面。
上拉加载
上拉加载的实现方式与下拉刷新类似,也是通过监听滚动事件,并判断滚动到底部触发相应的操作
使用antd-mobile分别实现上拉加载下拉刷新的效果:
下拉刷新效果代码:
HTML代码:
<>
{data.map((item, index) => ({item} ))}
>
JS代码:
import React, { useState } from 'react';
import { InfiniteScroll, List, DotLoading } from 'antd-mobile';
import { sleep } from 'antd-mobile/es/utils/sleep'
const result = [
{ id: 1, name: '展示1', status: true },
{ id: 2, name: '展示2', status: true },
{ id: 3, name: '展示3', status: true },
{ id: 4, name: '展示4', status: true },
{ id: 5, name: '展示5', status: true },
{ id: 6, name: '展示6', status: true },
{ id: 8, name: '展示8', status: true },
{ id: 9, name: '展示9', status: true },
{ id: 10, name: '展示10', status: true },
{ id: 11, name: '展示11', status: true },
{ id: 12, name: '展示12', status: true },
{ id: 13, name: '展示13', status: true },
{ id: 14, name: '展示14', status: true },
{ id: 15, name: '展示15', status: true },
{ id: 1, name: '展示1', status: true },
{ id: 2, name: '展示2', status: true },
{ id: 3, name: '展示3', status: true },
{ id: 4, name: '展示4', status: true },
{ id: 5, name: '展示5', status: true },
{ id: 6, name: '展示6', status: true },
{ id: 8, name: '展示8', status: true },
{ id: 9, name: '展示9', status: true },
{ id: 10, name: '展示10', status: true },
{ id: 11, name: '展示11', status: true },
{ id: 12, name: '展示12', status: true },
{ id: 13, name: '展示13', status: true },
{ id: 14, name: '展示14', status: true },
{ id: 15, name: '展示15', status: true },
]
let count = 0
async function mockRequest() {
if (count >= (result.length) / 2) {
return []
}
await sleep(2000)
count++
let arr = []
result.splice(0, 5).map(i => {
arr.push(i.name)
})
return arr
}
const InfiniteScrollContent = ({ hasMore }) => {
return (<>
{hasMore ? (<>
Loading
>) : (--- 我是有底线的 ---)}
>);
};
export default () => {
const [data, setData] = useState([]);
const [hasMore, setHasMore] = useState(true);
async function loadMore() {
const append = await mockRequest();
setData(val => [...val, ...append]);
setHasMore(append.length > 0);
}
return (
);
};
效果如下:
上拉加载效果代码:
HTML代码:
{
await sleep(1000);
setData([...getNextData(), ...data]);
}} renderText={status => {
return {statusRecord[status]};
}}>
{data.map((item, index) => ({item} ))}
JS代码:
import React, { useState } from 'react';
import { PullToRefresh, List } from 'antd-mobile';
import { sleep } from 'antd-mobile/es/utils/sleep';
import { LoremIpsum } from 'lorem-ipsum'
const lorem = new LoremIpsum({
sentencesPerParagraph: {
max: 8,
min: 4,
},
wordsPerSentence: {
max: 16,
min: 4,
},
})
function getNextData() {
const ret = [];
for (let i = 0; i < 18; i++) {
ret.unshift(lorem.generateWords(1));
}
return ret;
}
const statusRecord = {
pulling: '用力拉',
canRelease: '松开吧',
refreshing: '玩命加载中...',
complete: '好啦',
};
export default () => {
const [data, setData] = useState(() => getNextData());
return (
);
};
效果如下: