自学内容网 自学内容网

grid 布局react组件可以循数据自定义渲染某个数据 ,或插入某些数据在某个索引下

import React from "react";
import "./App.css"; // 引入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%;
}

效果图


原文地址:https://blog.csdn.net/qq_41798568/article/details/145258299

免责声明:本站文章内容转载自网络资源,如侵犯了原著者的合法权益,可联系本站删除。更多内容请关注自学内容网(zxcms.com)!