React中实现行等高的虚拟列表加载滚动

前言:当一个页面中需要接受接口返回的全部数据进行页面渲染时间,如果数据量比较庞大,前端在渲染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;
}

  • 9
    点赞
  • 10
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

小灰灰学编程

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值