HTML table reactjs 中的行跨度

HTML table rowspan in reactjs

当我使用地图并想像这样table时我感到困惑

有数据

const arr =[{
no: 1,
name:'david',
fruit: 'apple',
type:[{ typeName:'red apple'},{typeName:'green apple'}]
},
{
no: 2,
name: 'david',
fruit: 'orange',
type:[{ typeName:'mandarin orange'},{typeName:'bergamot orange'}]
}
]

我已经尝试过了,但是我卡住了,我只能这样做

我很困惑如何在这个 table

中合并“david”

我解决了这个问题。请检查 this code

// App.js
import "./styles.css";
import React, { Fragment } from "react";

export default function App() {
  const arr = [
    {
      no: 1,
      name: "david",
      fruit: "apple",
      type: [{ typeName: "red apple" }, { typeName: "green apple" }]
    },
    {
      no: 2,
      name: "david",
      fruit: "orange",
      type: [{ typeName: "mandarin orange" }, { typeName: "bergamot orange" }]
    },
    {
      no: 3,
      name: "jason",
      fruit: "orange",
      type: [{ typeName: "mandarin orange" }, { typeName: "bergamot orange" }]
    }
  ];

  let namesArr = {};
  const rowSpan = arr.reduce((result, item, key) => {
    if (namesArr[item.name] === undefined) {
      namesArr[item.name] = key;
      result[key] = 1;
    } else {
      const firstIndex = namesArr[item.name];
      if (
        firstIndex === key - 1 ||
        (item.name === arr[key - 1].name && result[key - 1] === 0)
      ) {
        result[firstIndex]++;
        result[key] = 0;
      } else {
        result[key] = 1;
        namesArr[item.name] = key;
      }
    }
    return result;
  }, []);

  return (
    <div>
      <table>
        <tr>
          <th>no</th>
          <th>name</th>
          <th>fruit</th>
          <th>type</th>
        </tr>
        {arr.map((el, index) => (
          <tr>
            <td>{el.no}</td>
            {rowSpan[index] > 0 && <td rowSpan={rowSpan[index]}>{el.name}</td>}
            <td>{el.fruit}</td>
            <td style={{}}>
              {el.type.length &&
                el.type.map((ele, i) => (
                  <Fragment>
                    <tr
                      style={{
                        border: "none",
                        display: "flex",
                        flexWrap: "wrap"
                      }}
                    >
                      <td
                        style={{
                          border: "none",
                          width: "100%",
                          borderTop: i > 0 ? "1px solid black" : "none"
                        }}
                      >
                        {ele.typeName}
                      </td>
                    </tr>
                  </Fragment>
                ))}
            </td>
          </tr>
        ))}
      </table>
    </div>
  );
}
// styles.css
table,
th,
td {
  border: 1px solid black;
  border-collapse: collapse;
}