当前位置:首页 > React

react windowing实现

2026-01-26 13:53:24React

React Windowing 实现方法

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

使用 react-window 库

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

安装依赖:

npm install react-window

固定高度列表示例:

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 提供更多功能但体积较大,适合复杂场景。

安装:

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>
  );
};

react windowing实现

标签: reactwindowing
分享给朋友:

相关文章

电脑如何安装react

电脑如何安装react

安装 Node.js 和 npm React 依赖于 Node.js 和 npm(Node Package Manager)。从 Node.js 官网下载并安装最新稳定版本,安装完成后会自动包含 np…

如何react页面

如何react页面

创建 React 页面 使用 create-react-app 快速初始化项目: npx create-react-app my-app cd my-app npm start 基础页面结构 在…

如何记忆react

如何记忆react

理解核心概念 React的核心概念包括组件、状态(state)、属性(props)、生命周期方法(类组件)和钩子(函数组件)。掌握这些基础概念是记忆React的关键。组件是React应用的构建块,分为…

react如何运行

react如何运行

运行React项目的步骤 安装Node.js 确保系统已安装Node.js(建议版本12以上),可从官网下载并安装。Node.js自带npm包管理器,用于后续依赖安装。 创建React项目 使用官…

react如何调试

react如何调试

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

react架构如何

react架构如何

React 架构核心概念 React 的架构围绕组件化、虚拟 DOM 和单向数据流设计。组件是构建用户界面的独立模块,分为函数组件和类组件。虚拟 DOM 通过高效的 Diff 算法减少直接操作真实 D…