长列表优化虚拟滚动

<!doctype html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Document</title>
    <style>
      ul.container {
        position: relative;
        width: 500px;
        max-height: 500px;
        /* 限定容器展示区域的大小 */
        margin: 0;
        padding: 0;
        border: 1px solid #000;
        overflow-y: auto;
        list-style-type: none;
      }
  
      ul.container li {
        position: absolute;
        width: 100%;
        height: 50px;
        color: white;
        text-align: center;
        line-height: 50px;
      }
    </style>
</head>
<body>
    <ul class="container"></ul>
    <script>
    const dataList = Array.from({ length: 1000 }).map((item, index) => index); // 生成一千条数据
    const $list = document.querySelector(".container")
    const size = 20 // 可视区域10条,但是需要滚动 每次的条数就取20
    createItem(0) // 默认从0开始(i)
    $list.setAttribute("style", `height: ${50 * dataList.length}px;`); // 设置容器高度
    function handleScroll(e) { // 计算应该展示那些
      const i = Math.floor(e.target.scrollTop / 50);
      createItem(i);
    }

    function createItem(i) {
      $list.innerHTML = dataList.slice(i, i + size).map(
        item =>
          `<li style="top: ${item * 50}px; background: ${createHexColor()};">${item}</li>`)
        .join("");
      }
    $list.onscroll = throttle(handleScroll, 20); 
    function throttle(fn, delay) { // 滚动触发的事件
      let lastTime = 0;
        return function () {
          const nowTime = +new Date();
          if (nowTime - lastTime > delay) {
            fn.apply(this, arguments);
            lastTime = nowTime;
          }
        }
      }
      function createHexColor() {
        const colorStr = "6789abcdef",
        	len = colorStr.length;
        let colorVal = "#";
        for (let i = 0; i < 6; i++) {
          colorVal += colorStr[Math.floor(Math.random() * len)];
        }
        return colorVal
      }
    </script>
</body>
</html>
实现自动滚动虚拟列表,可以使用 React 的 `react-window` 库。这个库提供了一些组件来优化大型列表的性能,其中包括 `FixedSizeList` 和 `VariableSizeList` 组件。这两个组件都支持自动滚动。 下面是一个使用 `FixedSizeList` 组件实现自动滚动的示例: ```jsx import React, { useRef, useEffect } from 'react'; import { FixedSizeList } from 'react-window'; function VirtualList({ itemCount, itemSize, height }) { const listRef = useRef(null); useEffect(() => { if (listRef.current) { // 自动滚动到底部 listRef.current.scrollToItem(itemCount - 1); } }, [itemCount]); const renderRow = ({ index, style }) => { return ( <div style={style}> Row {index} </div> ); }; return ( <FixedSizeList ref={listRef} itemCount={itemCount} itemSize={itemSize} height={height} width="100%" > {renderRow} </FixedSizeList> ); } export default VirtualList; ``` 在这个组件中,我们使用了 `useRef` 钩子来获取 `FixedSizeList` 组件的引用,然后在 `useEffect` 钩子中调用 `scrollToItem` 方法来自动滚动列表的底部。`scrollToItem` 方法接收一个索引值作为参数,它会将该索引所对应的行滚动到可视区域内。 你可以将 `itemCount`、`itemSize` 和 `height` 作为 props 传递给 `VirtualList` 组件,它们分别表示列表的行数、每行的高度和列表的高度。在 `renderRow` 函数中,我们根据索引值渲染每一行的内容。 这个组件可以像下面这样使用: ```jsx function App() { return ( <div> <h1>Virtual List</h1> <VirtualList itemCount={1000} itemSize={50} height={500} /> </div> ); } export default App; ``` 在这个示例中,我们创建了一个包含 1000 行的虚拟列表,每行的高度为 50 像素,列表的高度为 500 像素。当组件挂载时,它会自动滚动列表的底部。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值