当前位置: 首页 > news >正文

React 图片瀑布流

 思路:

根据浏览器宽度,确定列数,请求的图片列表数据是列数的10倍,按列数取数据渲染

Index.js:

import React from 'react'
import { connect } from 'react-redux'
import { withRouter } from 'react-router-dom'
import { SinglePageHeader } from '../../../../../components/light'
import InfiniteScroll from 'react-infinite-scroll-component'
import { Divider, Skeleton } from 'antd'
import useList from './useList'
import LazyLoad from 'react-lazy-load'import './index.css'function Index(props) {const {dataSource,isHasMore,columnCount,handleSearch,handleImgDrawSameStyleClick,} = useList(props)return (<div className="m-ai-img-wrap-box"><div className={`m-ai-img-wrap-chat`}><SinglePageHeader title="AI绘画作品展示"></SinglePageHeader><div className="m-ai-img-list" id="scrollableDiv"><InfiniteScrolldataLength={dataSource.length}next={handleSearch}refreshFunction={() => handleSearch({ page: 1, isRefresh: true })}pullDownToRefreshpullDownToRefreshThreshold={50}pullDownToRefreshContent={<h3 style={{ textAlign: 'center' }}>&#8595; 下拉刷新</h3>}releaseToRefreshContent={<h3 style={{ textAlign: 'center' }}>&#8593; 释放刷新</h3>}hasMore={isHasMore}loader={<Skeletonavatarparagraph={{rows: 3,}}activeclassName="m-h5-lesson-play-skeleton"/>}endMessage={dataSource.length === 0 ? null : (<Divider plain>已经到底啦~</Divider>)}scrollableTarget="scrollableDiv"><div className="m-ai-img-list-inner">{Array.from({ length: columnCount }, () => '').map((item, index) => (<div className="m-ai-img-list-column" key={index}>{dataSource.filter((item, dataSourceIndex) =>dataSourceIndex % columnCount === index).map((item) => (<div key={item.imgUid}><LazyLoad className="m-ai-img-lazy-load"><imgsrc={item.imgUrlCdn}className="m-ai-img"alt="图片"onClick={() => handleImgDrawSameStyleClick(item)}></img></LazyLoad></div>))}</div>))}</div>{dataSource.length === 0 ? (<Skeletonavatarparagraph={{rows: 3,}}activeclassName="m-h5-lesson-play-skeleton"/>) : null}</InfiniteScroll></div></div></div>)
}const mapStateToProps = (state) => {return {collapsed: state.getIn(['light', 'collapsed']),isRNGotToken: state.getIn(['light', 'isRNGotToken']),}
}const mapDispatchToProps = (dispatch) => {return {onSetState(key, value) {dispatch({ type: 'SET_LIGHT_STATE', key, value })},onDispatch(action) {dispatch(action)},}
}export default connect(mapStateToProps, mapDispatchToProps)(withRouter(Index))

useList.js:

import { useState, useEffect } from 'react'
import { Form } from 'antd'
import Api from '../../../../../api'
import { message } from 'antd'
import * as clipboard from 'clipboard-polyfill/text'export default function useList(props) {const [total, setTotal] = useState(10)const [current, setCurrent] = useState(1)let tempCount = Math.floor((window.innerWidth - 10) / 180)tempCount = Math.floor((window.innerWidth - (5 + tempCount * 5)) / 180)console.log('tempCount1', tempCount)//把dataSource和pageSize单独放在一起是为了避免切换pageSize时的bugconst [state, setState] = useState({dataSource: [],pageSize: tempCount * 10,})const [isHasMore, setIsHasMore] = useState(true)// eslint-disable-next-lineconst [username, setUsername] = useState(localStorage.getItem('username'))const [form] = Form.useForm()// eslint-disable-next-lineconst [initValues, setInitValues] = useState({})// eslint-disable-next-lineconst [columnCount, setColumnCount] = useState(tempCount)//搜索const handleSearch = ({page = current,pageSize = state.pageSize,isRefresh = false,} = {}) => {if (isRefresh) {setState({dataSource: [],pageSize: tempCount * 10,})}let searchData = { pageNum: page, pageSize }Api.h5.sdImgSearch(searchData).then((res) => {if (res.code === 200) {const { pageNum, pageSize, total } = res.datalet list = res.data.listif (isRefresh) {setState({dataSource: [...list],pageSize: res.data.pageSize,})} else {setState({dataSource: [...state.dataSource, ...list],pageSize: res.data.pageSize,})}setTotal(res.data.total)const currentTemp = res.data.pageNum + 1setCurrent(currentTemp)setIsHasMore(pageNum < Math.ceil(total / pageSize))}})}//添加或编辑const handleFinish = (values) => {console.log('Success:', values)Api.h5.exchangeCodeAppUse(values).then((res) => {if (res.code === 200) {message.success('恭喜您,兑换成功')//props.history.push('/h5/index/me')}})}//校验失败const handleFinishFailed = (errorInfo) => {console.log('Failed:', errorInfo)}//退出const handleQuit = () => {Api.light.userLogout().then((res) => {if (res.code === 200) {props.history.push('/h5/login')window.localStorage.removeItem('username')window.localStorage.removeItem('token')}})}//跳转const handleJumpPage = (path) => {// eslint-disable-next-lineprops.history.push(path)}const handleCopy = (text) => {clipboard.writeText(text).then(() => {message.success('复制成功')})}const handleImgDrawSameStyleClick = (item) => {console.log(item)props.history.push(`/single/home/sdSimple?modelId=${item.id}&name=${item.name}&link=${item.link}&imgUid=${item.imgUid}`)}useEffect(() => {if (window.platform === 'rn') {if (props.isRNGotToken === true) {handleSearch()}} else {handleSearch()}// eslint-disable-next-line}, [props.isRNGotToken])return {username,form,initValues,dataSource: state.dataSource,total,current,pageSize: state.pageSize,isHasMore,columnCount,handleFinish,handleFinishFailed,handleQuit,handleJumpPage,handleCopy,handleSearch,handleImgDrawSameStyleClick,}
}

index.css:

.m-ai-img-wrap-box{display: flex;justify-content: center;background: #ddd;background: #ddd;position: absolute;top: 0;left: 0;right: 0;bottom: 0;overflow: hidden;}
.m-ai-img-wrap-chat{position: relative; display: flex;flex-direction: column;width: 100%;background: #ededed;}
.m-ai-img-main{flex:1;display: flex;flex-direction: column;overflow-y: auto;}
.m-ai-img-list{flex: 1;padding: 0px 0;overflow-y: auto;}
.m-ai-img-list-inner{position: relative;padding: 0 0 0 5px; display: flex; flex-wrap: wrap;justify-content: center;}
.m-ai-img-list-column{display: flex;flex-direction: column;width: 175px;margin: 0 5px 0 0;}
.m-ai-img-lazy-load{position: relative;min-width: 175px; display: flex;flex-direction: column;justify-content: center; min-height: 175px;margin: 0 0 5px 0;border-radius: 5px; background: #dddddd;}
.m-ai-img{width: 175px;border-radius: 5px;}

效果图:

参考链接:

https://chat.xutongbao.top/

http://www.lryc.cn/news/206874.html

相关文章:

  • C++数据结构X篇_21_插入排序(稳定的排序)
  • 【Unity】3D跑酷游戏
  • bp前端验证码绕过及token绕过
  • Jmeter(十四):跨线程组传递jmeter变量及cookie的处理详解
  • css实现圆形进度条
  • 适用于 Windows 10 和 Windows 11 设备的笔记本电脑管理软件
  • YOLOv5论文作图教程(1)— 软件介绍及下载安装(包括软件包+下载安装详细步骤)
  • AutoCAD 2024 Mac中文附激活补丁 兼容M1.M2电脑
  • Jmeter基础---while控制器举例说明
  • 正点原子嵌入式linux驱动开发——RGB转HDMI
  • 前端时间分片渲染
  • 亿图导出word和PDF中清晰度保留方法
  • chatGPT结构及商业级相似模型应用调研
  • HarmonyOS鸿蒙原生应用开发设计- 华为分享图标
  • Java基础-反射
  • 计算机毕设 大数据二手房数据爬取与分析可视化 -python 数据分析 可视化
  • 【转载】 Bytedance火山引擎智能拥塞控制算法 VICC
  • Postman如何测试WebService接口
  • 微服务-Eureka
  • 超声电机工作原理
  • 基于人工蜂鸟优化的BP神经网络(分类应用) - 附代码
  • 两个list中存放相同的对象,一个是页面导入,一个是从数据库查询,外部传入一个集合存放的是对象的属性名称,根据属性名称处理两个list
  • 为什么C++能搜到的框架介绍都好抽象?
  • 人工智能(6):机器学习基础环境安装与使用
  • 电力巡检/电力抢修行业解决方案:AI+视频技术助力解决巡检监管难题
  • 区块链轻节点的问答
  • 常用Web安全扫描工具汇整
  • 查看当前cmake版本支持哪些版本的Visual Studio
  • 岩土工程桥梁监测中智能振弦传感器的应用方案
  • 上云容灾如何实现碳中和-万博智云受邀参加1024程序员节数据技术论坛并发表演讲