我不是反应虚拟化方面的专家,但似乎定义自定义overscanIndicesGetter
函数可能是最简单的解决方案。根据文档:
overscanIndicesGetter
这是高级属性。该函数负责计算指定范围前后过扫描的单元格数。默认情况下,React Virtualized 根据滚动方向优化过扫描单元的数量。如果您想自定义此行为,您可能需要分叉该
defaultOverscanIndicesGetter
功能。
在下面的代码片段中,我定义了一个始终返回overscanStartIndex
0 且overscanStopIndex
等于最后一个索引的函数:
const overscanIndicesGetter = ({cellCount}) => ({
overscanStartIndex: 0,
overscanStopIndex: cellCount - 1,
});
查看您的开发人员工具,您会发现它实际上渲染了所有 1,000 个单元格。
const { Grid } = window.ReactVirtualized;
const data = Array.from(new Array(1000)).map((_, i) => i);
const Cell = ({key, rowIndex, style}) =>
<div key={key} style={style}>{data[rowIndex]}</div>;
const overscanIndicesGetter = ({cellCount}) => ({
overscanStartIndex: 0,
overscanStopIndex: cellCount - 1,
});
const App = ({data}) => (
<Grid
cellRenderer={Cell}
columnCount={1}
columnWidth={100}
rowCount={data.length}
rowHeight={30}
height={300}
width={300}
overscanIndicesGetter={overscanIndicesGetter}
/>
);
ReactDOM.render(<App data={data}/>, document.querySelector('div'));
<link rel="stylesheet" src="https://unpkg.com/react-virtualized@9.2.2/styles.css"></link>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.4.2/react.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.4.2/react-dom.min.js"></script>
<script src="https://unpkg.com/react-virtualized@9.2.2/dist/umd/react-virtualized.js"></script>
<div></div>
如果你愿意,你可以尝试让它更智能。例如,如果您能够根据可见单元格的索引计算下一个“prod”单元格(即确定可见单元格是否有蓝线的单元格)的索引,则可以将函数修改为为 .返回该索引overscanStopIndex
。内置defaultOverscanIndicesGetter
函数记录了您的函数将收到的所有值。
/**
* Calculates the number of cells to overscan before and after a specified range.
* This function ensures that overscanning doesn't exceed the available cells.
*
* @param cellCount Number of rows or columns in the current axis
* @param scrollDirection One of SCROLL_DIRECTION_BACKWARD or SCROLL_DIRECTION_FORWARD
* @param overscanCellsCount Maximum number of cells to over-render in either direction
* @param startIndex Begin of range of visible cells
* @param stopIndex End of range of visible cells
*/
如果您有大量数据,那么值得您花时间看看可以用这些数据做什么。