有没有一种方法可以根据值使用 react-table 来设置单个单元格的样式?

Is there a way to style individual cell using react-table based on the value?

我想在 react-table 中设置单个单元格的样式,但我做不到。

const MOCK_DATA = [
  {
    amount: 1000,
    status: `SUCCESS`,
    updatedAt: 1629181927,
  },
  {
    amount: 2000,
    status: `FAILED`,
    updatedAt: 1629181927,
  },
];
export const COLUMNS = [
  {
    Header: 'Date',
    accessor: 'transactionDate',
  },
  {
    Header: 'Amount',
    accessor: 'amount',
  },
  {
    Header: 'Status',
    accessor: 'status',
  },
];

这是 jsx:

 <tbody {...getTableBodyProps()}>
        {rows.map(row => {
          prepareRow(row);
          return (
            <tr {...row.getRowProps()}>
              {row.cells.map(cell => (
                <td {...cell.getCellProps()}>{cell.render('Cell')}</td>
              ))}
            </tr>
          );
        })}
      </tbody>

假设我想根据数据的状态将单元格的颜色更改为绿色或红色,我该如何实现?

注:

您可以使用 status 来定义 class

 <tr {...row.getRowProps()} className={row.status === 'SUCCESS' ? 'active': 'warning'}>
              {row.cells.map(cell => (
                <td {...cell.getCellProps()}>{cell.render('Cell')}</td>
              ))}
            </tr>

您可以使用 react-table 中的自定义单元格渲染选项。

  {
        Header: "Status",
        accessor: "status",
        Cell: (props) => {
          return (
            <p style={{ color: props.value === "SUCCESS" ? "green" : "red" }}>
              {props.value}
            </p>
          );
        }
      }

Working Sandbox

当有多个状态并且需要为每个状态显示不同的颜色时,我们可以维护一个地图。

const statusColorMap =  {
  SUCCESS: 'green',
  FAILED: 'red',
  PENDING: 'yellow'
  // etc 
}

现在我们可以做到了

<p style={{ color: statusColorMap[props.value] }}>{props.value}</p>;