使用React Table逐行显示对象的数组?

问题描述 投票:0回答:1

我想逐行显示电影而不更改data模型。

这是我的代码:

import * as React from "react";
import { useTable } from "react-table";

const borderStyle = {
  border: "1px dashed navy"
};

export default function App() {
  const data = React.useMemo(
    () => [
      {
        actor: "Johnny Depp",
        movies: [
          {
            name: "Pirates of the Carribean 1"
          },
          {
            name: "Pirates of the Carribean 2"
          },
          {
            name: "Pirates of the Carribean 3"
          },
          {
            name: "Pirates of the Carribean 4"
          }
        ]
      }
    ],
    []
  );
  const columns = React.useMemo(
    () => [
      {
        Header: "Actor",
        accessor: "actor",
      },
      {
        Header: "Movies",
        accessor: (row, index) => {
          console.log({ row });
          // i want to display this row-by-row instead of in 1-row without changing data model
          return row.movies.map(movie => movie.name);
        }
      }
    ],
    []
  );
  const {
    getTableProps,
    getTableBodyProps,
    headerGroups,
    rows,
    prepareRow
  } = useTable({ columns, data });
  return (
    <table {...getTableProps()}>
      <thead>
        {headerGroups.map(headerGroup => (
          <tr {...headerGroup.getHeaderGroupProps()}>
            {headerGroup.headers.map(column => (
              <th {...column.getHeaderProps()} style={borderStyle}>
                {column.render("Header")}
              </th>
            ))}
          </tr>
        ))}
      </thead>
      <tbody {...getTableBodyProps()}>
        {rows.map((row, i) => {
          prepareRow(row);
          if (i == 0) {
            console.log({ row });
          }
          return (
            <tr {...row.getRowProps()}>
              {row.cells.map((cell, j) => {
                if (i == 0 && j < 2) {
                  console.log({ cell, i, j });
                }
                return (
                  <td
                    {...cell.getCellProps()}
                    style={borderStyle}
                  >
                    {cell.render("Cell")}
                  </td>
                );
              })}
            </tr>
          );
        })}
      </tbody>
    </table>
  );
}

当前看起来像:

这是它的直接链接:https://codesandbox.io/s/modest-sanderson-z0keq?file=/src/App.tsx

我的电影列表是一个对象数组,因此如何在演员名称旁边显示它?所以看起来像:

table

我想在不更改数据模型的情况下逐行显示电影。这是我的代码:import * as React from“ react”;从“反应表”导入{useTable}; const borderStyle = {border:“ 1px ...

javascript reactjs react-table
1个回答
0
投票
没有其他方法可以做到,除了像提到库的作者那样将数据展平外,这就是我的做法:
© www.soinside.com 2019 - 2024. All rights reserved.