前言:当一个页面中需要接受接口返回的全部数据进行页面渲染时间,如果数据量比较庞大,前端在渲染dom的过程中需要花费时间,造成页面经常出现卡顿现象。
需求:通过虚拟加载,优化页面渲染速度
缺点:需要固定好每一行元素的高度
行元素不等高的虚拟列表实现方法
实现方法:
策略:设置可视区域高度、滚动高度、每个元素高度、初始展示的元素数据,通过监听滚动条滚动高度,根据高度重新获取需要展示的数据进行遍历
export default class Cp extends Component {
constructor(props){
super(props)
this.state = {
dataListTotal: 100,
// 元素总数据
dataList: new Array(100).fill().map((item,index)=>index+1),
// 初始展示数据
showDataList: new Array(20).fill().map((item,index)=>index+1),
// 每个元素高度
itemHeight: 20,
// 可视区域高度
viewHeight: 300
}
}
handleScrollChange = (e)=>{
const {itemHeight, viewHeight, dataList} = this.state
// 获取滚动距离
let scrollTop = e.target.scrollTop;
// 初始元素索引 = 滚动距离 / 每一项的高度
const startIndex = Math.round(scrollTop / itemHeight);
// 结束元素索引 = 初始索引 + 容器高度 / 每一项的高度
const endIndex = startIndex + viewHeight / itemHeight;
// 截取数据
let showDataList = dataList.slice(startIndex, endIndex);
this.setState({
showDataList,
scrollTop,
})
}
render(){
const {showDataList, scrollTop} = this.state
console.log(showDataList, 'showDataList')
return <div className='container' onScroll={this.handleScrollChange}>
// 可视区域,撑起内部高度,让外层容器产生滚动条
<div className='scroll-container'></div>
// 元素区域,transform:给元素容器设置偏移量,让元素在可视区域内呈现
<div className='item-container' style={{transform: 'translateY(' + scrollTop + 'px)',}}>
{
Array.isArray(showDataList) && showDataList.length > 0
? showDataList.map(item=>{
return <div className='item-content'>{item}</div>
})
: null
}
</div>
</div>
}
}
// 可视区域容器的样式
.container {
width: 200px;
height: 300px;
border: 1px solid #ff6d00;
overflow-y: scroll;
position: relative;
}
// 滚动容器的样式
.scroll-container {
height: 2000px;
}
// 每个元素的容器样式
.item-container {
position: absolute;
top: 0;
left: 0;
}
.item-content {
height: 20px;
}