ant design 的表格懒加载
大家好,我是一名,跨境行业 saas 软件开发的前端程序员,阿毛
这个我的个人网站
我们公司的一个项目前端是用 ant design 开发的,这个表格内的东西比较多, 导致比较卡,本来想说用虚拟列表的,只加一个配置就行了,但是在表格内部又多一个滚动条,影响用户体验, 想到了懒加载,调研了一下,这里就做了一个 demo 来看看效果。
我这里点击 load 加载了一个 50 列,1000 行的 表格, 感觉还行,没有什么卡顿。
这里是用了 react-lazyload 这个库 ,这里简单讲一下使用步骤
-
安装
- yarn add react-lazyload
- yarn add @types/react-lazyload
- yarn add prop-types
-
在 antd 中使用
- placeholder 可以写未加载时显示的东西 我这里不显示 为null
- height 为这个组件 未加载时的 站位高度
- scrollContainer 是一个很重要的配置, 是你滚动的的那个dom元素, 这里是body 就不用配置了
- 还有一些其他配置可自行查阅
<Table
sticky
loading={loading}
dataSource={data}
columns={columns}
scroll={{ x: 800 }}
components={{
body: {
row: (_props) => {
return (
<LazyLoad placeholder={null} height={54}>
<tr {..._props} />
</LazyLoad>
);
},
},
}}
pagination={false}
/>
- 样式修复
使用 react-lazyload 进行懒加载时, 它会默认给你加一个 类为 lazyload-wrapper 的 div 来进行包裹, 在其他地方可能影响不大, 但是在表格中,如果你有一些自己的样式,就会被影响到, 这里为了消除影响, 让 lazyload-wrappe 下 有 tr 的 div 不参与样式计算中,这样来消除影响。
/* 样式 */
div.lazyload-wrapper:has(> tr) {
display: contents !important;
}
以下是demo 的全部代码
import { useMemo, useState } from 'react'
import LazyLoad from 'react-lazyload';
import './App.css'
import { Button, Table } from 'antd'
import { ColumnsType } from 'antd/es/table';
function App() {
const [loading, setLoading] = useState(false)
const [data, setData] = useState([])
const columns: ColumnsType<any> = useMemo(() => {
const arr = []
for (let i = 0; i < 50; i++) {
const str = "value" + i
arr.push(
{
title: str,
dataIndex: str,
key: str,
width: 100,
render: (text) => {
return (
<span>{text}</span>
)
}
}
)
}
return arr
}, [])
function getData() {
const arr = []
console.log('run loading')
setLoading(true)
setTimeout(() => {
for (let j = 0; j < 1000; j++) {
const obj: any = {}
for (let i = 0; i < 50; i++) {
obj[`value${i}`] = Math.random()
}
arr.push(obj)
}
console.log('OK')
console.log(arr)
setData(arr)
setLoading(false)
}, 1000);
}
return (
<>
<Button onClick={() => getData()}>load</Button> {data.length}
<Table
sticky
loading={loading}
dataSource={data}
columns={columns}
scroll={{ x: 800 }}
components={{
body: {
row: (_props) => {
return (
<LazyLoad placeholder={null} height={54}>
<tr {..._props} />
</LazyLoad>
)
}
}
}}
pagination={false}
/>
</>
)
}
export default App