当前位置:首页 > React

react windowing实现

2026-01-26 13:53:24React

React Windowing 实现方法

React windowing 是一种优化长列表渲染性能的技术,通过仅渲染可见区域内的元素来减少 DOM 节点数量。以下是几种常见的实现方式:

使用 react-window 库

react-window 是 react-virtualized 的轻量级替代方案,适合大多数列表虚拟化场景。

安装依赖:

npm install react-window

固定高度列表示例:

react windowing实现

import { FixedSizeList as List } from 'react-window';

const Row = ({ index, style }) => (
  <div style={style}>Row {index}</div>
);

const Example = () => (
  <List
    height={400}
    itemCount={1000}
    itemSize={35}
    width={300}
  >
    {Row}
  </List>
);

可变高度列表:

import { VariableSizeList as List } from 'react-window';

const rowHeights = new Array(1000)
  .fill(true)
  .map(() => 25 + Math.round(Math.random() * 50));

const Row = ({ index, style }) => (
  <div style={style}>Row {index}</div>
);

const Example = () => (
  <List
    height={400}
    itemCount={1000}
    itemSize={index => rowHeights[index]}
    width={300}
  >
    {Row}
  </List>
);

使用 react-virtualized

react-virtualized 提供更多功能但体积较大,适合复杂场景。

安装:

react windowing实现

npm install react-virtualized

基本实现:

import { List } from 'react-virtualized';

const list = Array(1000).fill().map((_, index) => `Item ${index}`);

function rowRenderer({ key, index, style }) {
  return (
    <div key={key} style={style}>
      {list[index]}
    </div>
  );
}

const Example = () => (
  <List
    width={300}
    height={400}
    rowCount={list.length}
    rowHeight={30}
    rowRenderer={rowRenderer}
  />
);

自定义实现

对于简单需求可以手动实现虚拟滚动:

function VirtualList({ items, itemHeight, containerHeight }) {
  const [scrollTop, setScrollTop] = useState(0);
  const startIdx = Math.floor(scrollTop / itemHeight);
  const endIdx = Math.min(
    items.length - 1,
    Math.floor((scrollTop + containerHeight) / itemHeight)
  );

  return (
    <div
      style={{ height: containerHeight, overflow: 'auto' }}
      onScroll={e => setScrollTop(e.currentTarget.scrollTop)}
    >
      <div style={{ height: items.length * itemHeight }}>
        {items.slice(startIdx, endIdx + 1).map((item, i) => (
          <div
            key={startIdx + i}
            style={{
              position: 'absolute',
              top: (startIdx + i) * itemHeight,
              height: itemHeight
            }}
          >
            {item}
          </div>
        ))}
      </div>
    </div>
  );
}

性能优化建议

  • 对于动态内容,使用 useMemo 缓存计算结果
  • 避免在渲染函数中进行复杂计算
  • 对于非常长的列表,考虑分页加载
  • 使用 shouldComponentUpdateReact.memo 防止不必要的重新渲染

响应式处理

添加响应式支持确保在不同屏幕尺寸正常工作:

const useWindowSize = () => {
  const [size, setSize] = useState([0, 0]);
  useEffect(() => {
    function updateSize() {
      setSize([window.innerWidth, window.innerHeight]);
    }
    window.addEventListener('resize', updateSize);
    updateSize();
    return () => window.removeEventListener('resize', updateSize);
  }, []);
  return size;
};

const ResponsiveList = ({ items }) => {
  const [width, height] = useWindowSize();
  return (
    <FixedSizeList
      height={height * 0.8}
      width={width * 0.9}
      itemCount={items.length}
      itemSize={50}
    >
      {Row}
    </FixedSizeList>
  );
};

标签: reactwindowing
分享给朋友:

相关文章

如何降低react版本

如何降低react版本

降低 React 项目版本的步骤 检查当前 React 版本 在项目根目录的 package.json 文件中查看 dependencies 或 devDependencies 下的 react 和…

react如何更新

react如何更新

更新 React 版本的方法 检查当前 React 版本 运行以下命令查看项目中安装的 React 版本: npm list react 更新 React 及相关依赖 通过 npm 或 yarn…

react如何调试

react如何调试

调试 React 应用的方法 使用 React Developer Tools React Developer Tools 是 Chrome 和 Firefox 的浏览器扩展,可以检查组件树、状态和…

react如何刷新

react如何刷新

刷新React组件的方法 使用状态更新触发重新渲染 通过更新组件的状态可以触发重新渲染。React会在状态变化时自动重新渲染组件。 const [count, setCount] = useStat…

react如何发布

react如何发布

发布React应用的步骤 构建生产版本 使用以下命令生成优化后的生产版本代码,代码会被压缩并移除开发环境中的调试工具: npm run build 构建完成后会生成build文件夹,包含所有静态资源…

react如何启动

react如何启动

启动 React 项目的步骤 确保已安装 Node.js React 需要 Node.js 环境运行,建议安装最新稳定版(LTS)。可通过以下命令检查是否已安装: node -v npm -v…