示例工程 19-virtualized-lists
19-virtualized-lists/app/src/components/VirtualList.tsx
import {
useCallback,
useEffect,
useMemo,
useState,
type ReactNode,
type RefObject,
} from "react";
export type VirtualListProps<T> = {
items: T[];
height: number;
rowHeight: number | ((index: number) => number);
overscan?: number;
renderRow: (item: T, index: number) => ReactNode;
containerRef?: RefObject<HTMLDivElement | null>;
testId?: string;
onVisibleRange?: (start: number, end: number) => void;
onScrollTop?: (top: number) => void;
};
export function VirtualList<T>({
items,
height,
rowHeight,
overscan = 4,
renderRow,
containerRef,
testId = "virtual-row",
onVisibleRange,
onScrollTop,
}: VirtualListProps<T>) {
const [scrollTop, setScrollTop] = useState(0);
const offsets = useMemo(() => {
const next = new Array<number>(items.length + 1);
next[0] = 0;
for (let index = 0; index < items.length; index += 1) {
const size = typeof rowHeight === "number" ? rowHeight : rowHeight(index);
next[index + 1] = (next[index] ?? 0) + size;
}
return next;
}, [items.length, rowHeight]);
const total = offsets[items.length] ?? 0;
const findStart = useCallback(
(top: number): number => {
let low = 0;
let high = items.length - 1;
let result = 0;
while (low <= high) {
const mid = Math.floor((low + high) / 2);
if ((offsets[mid] ?? 0) <= top) {
result = mid;
low = mid + 1;
} else {
high = mid - 1;
}
}
return Math.max(0, result - overscan);
},
[items.length, offsets, overscan],
);
const start = findStart(scrollTop);
const budget = scrollTop + height;
let end = start;
while (end < items.length && (offsets[end] ?? 0) < budget) end += 1;
end = Math.min(items.length, end + overscan);
useEffect(() => {
onVisibleRange?.(start, end);
}, [end, onVisibleRange, start]);
return (
<div
ref={containerRef}
data-testid="virtual-list"
className="relative overflow-auto rounded-card border border-border bg-panel"
style={{ height }}
onScroll={(event) => {
setScrollTop(event.currentTarget.scrollTop);
onScrollTop?.(event.currentTarget.scrollTop);
}}
>
<div style={{ height: total, position: "relative" }}>
{items.slice(start, end).map((item, offset) => {
const index = start + offset;
const top = offsets[index] ?? 0;
const size = (offsets[index + 1] ?? top) - top;
return (
<div
key={index}
data-testid={testId}
data-row-index={index}
style={{
position: "absolute",
top,
left: 0,
right: 0,
height: size,
}}
>
{renderRow(item, index)}
</div>
);
})}
</div>
</div>
);
}