【react】react移动端函数组件瀑布流布局上拉加载更多
使用macy js库和antd-mobile库来实现
1、下载依赖
yarn add macy antd-mobile
或
npm i macy antd-mobile
2、废话不多说-直接上代码
import React, {useEffect, useState} from "react";
import Macy from 'macy'
import {DotLoading, InfiniteScroll} from "antd-mobile";
import { sleep } from 'antd-mobile/es/utils/sleep'
//后端返回的数据
const dataImages = [
"https://picsum.photos/640/200/?random",
"https://picsum.photos/360/640/?random",
"https://picsum.photos/480/720/?random",
"https://picsum.photos/480/640/?random",
"https://picsum.photos/360/?random",
"https://picsum.photos/360/520/?random",
"https://picsum.photos/520/360/?random",
"https://picsum.photos/520/360/?random",
"https://picsum.photos/520/360/?random",
"https://picsum.photos/720/640/?random",
]
//后端请求函数返回下一页的数据
let count = 0
export async function mockRequest() {
if (count >= 5) {
return []
}
await sleep(2000)
count++
return dataImages
}
//定义滚动到底部后触发的方法,并根据hasMore来判断要显示的内容
const InfiniteScrollContent = ({ hasMore }) => {
return (
<>
{hasMore ? (
<>
<span>Loading</span>
<DotLoading />
</>
) : (
<span>--- 我是有底线的 ---</span>
)}
</>
)
}
const Index = () => {
const [data, setData] = useState(dataImages)
const [hasMore, setHasMore] = useState(true)
const [masonry, setMasonry] = useState(null);
//触底后立即触发该方法
async function loadMore() {
const append = await mockRequest()
setData(val => [...val, ...append])
setHasMore(append.length > 0)
}
const getMacy =()=>{
if (masonry) {
//当数据更新时,会重新计算并排版
masonry.reInit()
} else {
let masonry = new Macy({
container: '.macy-container', // 图像列表容器
trueOrder: false,
waitForImages: false,
useOwnImageLoader: false,
debug: true,
margin: { x: 10, y: 15 }, // 设计列与列的间距
columns: 2, // 设置列数
})
setMasonry(masonry)
}
}
//当数据变化则调用getMacy,重新计算
useEffect(()=>{
getMacy()
},[data])
return (
<>
<div className="macy-container 其他的样式名">
{
data && data.map((item,index)=>{
return (
<img src={item} alt="" className="img_item" key={index}/>
)
})
}
</div>
<InfiniteScroll loadMore={loadMore} hasMore={hasMore}>
<InfiniteScrollContent hasMore={hasMore} />
</InfiniteScroll>
<>
);
};
export default Index;
效果演示
【react】react移动端瀑布流布局效果演示