我使用 React Virtualized 来显示一些项目。我现在的问题是如何为每个框添加边距以使每个框之间都有空间?
这是一个沙箱,你可以看到所有箱子都有边框,没有空间。我该如何添加空间?
这是我的列表代码
export function VirtualizedGrid<ItemType>({
items,
renderItem,
itemHeight,
itemMinWidth,
numColumns,
registerChild,
onRowsRendered
}: VirtualizedGridProps<ItemType>): JSX.Element {
const gridRef = useRef<any>(null);
const containerRef = useRef<any>(null);
const containerWidth = containerRef?.current?.clientWidth ?? 0;
const windowSize = useWindowSize();
useEffect(() => {
gridRef.current?.recomputeGridSize();
}, [windowSize]);
function calculateColumnCount(width: number) {
return Math.floor(width / itemMinWidth);
}
function calculateItemWidth(width: number, columnCount: number) {
return width / columnCount;
}
const columnCount = numColumns ?? calculateColumnCount(containerWidth);
const rowCount = Math.ceil(items.length / columnCount);
const itemWidth = calculateItemWidth(containerWidth, columnCount);
return (
<Container ref={containerRef}>
<WindowScroller>
{({ height, isScrolling, onChildScroll, scrollTop }) => (
<AutoSizer disableHeight>
{() => {
return (
<Grid
// ref={gridRef}
ref={(el) => {
registerChild(el);
gridRef.current = el;
}}
autoHeight
columnCount={columnCount}
columnWidth={itemWidth}
width={containerWidth}
height={height}
rowCount={rowCount}
rowHeight={itemHeight}
isScrolling={isScrolling}
scrollTop={scrollTop}
onScroll={onChildScroll}
cellRenderer={(props: GridCellProps) => {
const fullProps: VirtualizedGridItemProps<ItemType> = {
...props,
items,
columnCount: columnCount
};
return renderItem(fullProps);
}}
/>
);
}}
</AutoSizer>
)}
</WindowScroller>
</Container>
);
}
只需根据项目索引将条件填充添加到TestGridItem.tsx的容器元素即可。
这是基于您的代码的 Sandbox 示例