我使用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: 的 Container
元素import { motion } from "framer-motion";
import React from "react";
import styled from "styled-components";
import { VirtualizedGridItemProps } from "./interfaces";
/**
* Interfaces
*/
interface TestObject {
id: number;
name: string;
}
export interface TestGridItemProps
extends VirtualizedGridItemProps<TestObject> {}
/**
* Styles
*/
const Container = styled.div`
display: flex;
padding: 10px; // <<<<<<<<<<<<<< ADDED PADDING
`;
const Card = styled(motion.div)`
background: #111111;
border: 1px solid rgba(255, 255, 255, 0.1);
color: white;
display: flex;
align-items: center;
justify-content: center;
flex: 1;
height: 100%;
font-family: sans-serif;
font-weight: 600;
text-align: center;
padding: 12px;
`;
/**
* Component
*/
export function TestGridItem({
items,
columnCount,
rowIndex,
columnIndex,
style,
}: TestGridItemProps): JSX.Element {
const index = rowIndex * columnCount + columnIndex;
if (index > items.length - 1) {
return <></>;
}
return (
<Container style={style}>
<Card
variants={{
hidden: {
opacity: 0,
},
visible: {
opacity: 1,
},
}}
initial="hidden"
animate="visible"
>
{`${items[index].name} (ID: ${items[index].id})`}
</Card>
</Container>
);
}