高效渲染大型列表和表格数据的 React 组件,对List列表支持非常好,对表格支持不太好
react-window原理:通过绝对定位列表项(通过内联样式)来实现虚拟滚动
https://react-window.vercel.app/#/examples/list/memoized-list-items
https://react-window.vercel.app/#/examples/list/fixed-size
X,Y无限滚动用 Grid https://react-window.vercel.app/#/examples/grid/variable-size
react-window Table案例 react-window Table表格案例
Rendering large lists https://addyosmani.com/blog/react-window/
Virtualize large lists https://web.dev/virtualize-long-lists-react-window/
https://www.jianshu.com/p/40c4dd721c21

  1. yarn add react-window
  • VariableSizeGrid 动态栅格
  • VariableSizeList 动态列表
  • FixedSizeGrid 固定栅格
  • FixedSizeList 固定列表
  • areEqual
  • shouldComponentUpdate

instance 实例方法

  • resetAfterColumnIndex
  • resetAfterIndices
  • resetAfterRowIndex
  • resetAfterIndices
  • _getItemStyleCache
  • forceUpdate
  • scrollToItem

对比 react-virtualized

  • Gzip 2KB,Adding a react-window list to a CRA project increases the (gzipped) build size by <2 KB.
  • Gzip 34KB,Adding a react-virtualized list to a CRA project increases the (gzipped) build size by ~33.5 KB

AutoSizer自适应宽度

AutoSizer自适应宽高结合react-virtualized-auto-sizer使列表自适应当前页面的宽高
用AutoSizer可是列表宽高为当前父组件的100%

  1. npm i react-virtualized-auto-sizer react-window

AutoSizer demo

  1. import React from "react";
  2. import { FixedSizeList as List } from "react-window";
  3. import AutoSizer from "react-virtualized-auto-sizer";
  4. function Row({ index, style }){
  5. console.log('index',index, 'style', style)
  6. return (
  7. <div className={index % 2 ? "ListItemOdd" : "ListItemEven"} style={style}>
  8. Row {index}
  9. </div>
  10. );
  11. }
  12. function App() {
  13. return (
  14. <AutoSizer>
  15. {({ height, width }) => (
  16. <List
  17. className="List"
  18. height={height}
  19. itemCount={10000}
  20. itemSize={35}
  21. width={width}
  22. >
  23. {Row}
  24. </List>
  25. )}
  26. </AutoSizer>
  27. )
  28. }
  29. export default App;