import React from "react";
import "./App.css";
interface GridDisplayProps {
items: any[];
rowNum?: number;
renderItem?: (item: any, index: number) => React.ReactNode;
customElement?: React.ReactNode;
customIndex?: number;
}
const GridDisplay: React.FC<GridDisplayProps> = ({
items,
rowNum = 2,
renderItem,
customElement,
customIndex = 0,
}) => {
const defaultRenderItem = (item: any, index: number) =>
<div>{`这是默认渲染${index}`}</div>;
const modifiedItems = [...items];
if (customElement) {
const targetIndex = customIndex < items.length ? customIndex : 0;
modifiedItems.splice(targetIndex, 0, customElement);
}
const rows: any[] = modifiedItems.reduce((resultArray: any[], item, index) => {
const chunkIndex = Math.floor(index / rowNum);
if (!resultArray[chunkIndex]) {
resultArray[chunkIndex] = [];
}
resultArray[chunkIndex].push(item);
return resultArray;
}, []);
return (
<div className="container">
{rows.map((row, rowIndex) => (
<div className="row" key={rowIndex}>
{row.map((item: any, index: number) => {
const globalIndex = rowIndex * rowNum + index;
return (
<div
className="item"
key={index}
style={{ width: `${100 / rowNum}%` }}
>
{React.isValidElement(item)
? item
: renderItem
? renderItem(item, globalIndex)
: defaultRenderItem(item, globalIndex)}
</div>
);
})}
</div>
))}
</div>
);
};
export default GridDisplay;
.container {
display: flex;
flex-direction: column;
}
.row {
display: flex;
}
.item {
flex: 1;
width: 50%;
}