虚拟滚动列表在React中渲染空白,是哪里出错了?

打工人爱慧 阅读 3

我在用React实现一个长列表的虚拟滚动,数据有上万条,但页面只显示空白,滚动也没反应。我参考了网上的例子,用了固定高度和transform定位,但就是不渲染内容。

控制台没报错,数据也正常加载了,是不是我的计算逻辑有问题?下面是我的简化代码:

const VirtualList = ({ items, itemHeight = 50 }) => {
  const containerHeight = 600;
  const [scrollTop, setScrollTop] = useState(0);
  const visibleCount = Math.ceil(containerHeight / itemHeight);
  const startIdx = Math.floor(scrollTop / itemHeight);
  const visibleItems = items.slice(startIdx, startIdx + visibleCount);

  return (
    <div onScroll={(e) => setScrollTop(e.target.scrollTop)} style={{ height: containerHeight, overflow: 'auto' }}>
      <div style={{ height: items.length * itemHeight }} />
      {visibleItems.map((item, i) => (
        <div key={startIdx + i} style={{ height: itemHeight, transform: <code>translateY(${(startIdx + i) * itemHeight}px)</code> }}>
          {item.name}
        </div>
      ))}
    </div>
  );
};
我来解答 赞 1 收藏
二维码
手机扫码查看
暂无解答

暂无解答