如何将道具传递给反应表中的行

Mai*_*kol 5 reactjs react-table react-table-v7

我一直在关注https://blog.logrocket.com/complete-guide-building-smart-data-table-react/。要根据单元格值应用自定义样式,我正在更新列对象,如下所示:

return {
  Header: key,
  accessor: key,
  width: "150",
  sortType: "basic",
  Cell: ({cell: {value} }) => {
    if (value == "Error") {
      return <RedCell/>
    }
    ...
  }
}
Run Code Online (Sandbox Code Playgroud)

是否可以将自定义样式应用于包含单元格的行?我想必须将道具传递给行,但我根本不清楚如何做到这一点。

任何指针将不胜感激。

GPX*_*GPX 9

对于任何偶然发现这个问题的人,库的作者已经回答了这个问题react-table\xe2\x80\x94 https://spectrum.chat/react-table/general/v7-row-getrowprops-how-to-pass-自定义道具到行~ff772376-0696-49d6-b259-36ef4e558821

\n

rowProps在 Table 组件中,您可以为行 \xe2\x80\x94传递您选择的任何属性(例如)

\n
<Table\n        columns={columns}\n        data={data}\n        rowProps={row => ({\n          onClick: () => alert(JSON.stringify(row.values)),\n          style: {\n            cursor: "pointer"\n          }\n        })}\n      />\n
Run Code Online (Sandbox Code Playgroud)\n

然后实际使用这个\xe2\x80\x94

\n
function Table({ columns, data, rowProps = () => ({}) }) {\n  // Use the state and functions returned from useTable to build your UI\n  const { getTableProps, headerGroups, rows, prepareRow } = useTable({\n    columns,\n    data\n  });\n\n  // Render the UI for your table\n  return (\n    <table {...getTableProps()}>\n      <thead>\n        {headerGroups.map(headerGroup => (\n          <tr {...headerGroup.getHeaderGroupProps()}>\n            {headerGroup.headers.map(column => (\n              <th {...column.getHeaderProps()}>{column.render("Header")}</th>\n            ))}\n          </tr>\n        ))}\n      </thead>\n      <tbody>\n        {rows.map(\n          (row, i) =>\n            prepareRow(row) || (\n              <tr {...row.getRowProps(rowProps(row))}>\n                {row.cells.map(cell => {\n                  return (\n                    <td {...cell.getCellProps()}>{cell.render("Cell")}</td>\n                  );\n                })}\n              </tr>\n            )\n        )}\n      </tbody>\n    </table>\n  );\n}\n
Run Code Online (Sandbox Code Playgroud)\n


Tom*_*Tom 1

当前您正在将样式应用于列定义。

为了将样式应用于整个行。(例如,如果值==“错误”,则将整行设为红色),我会在您的表 UI 中执行此操作。

在您的 UI 中,您将调用该行prepareRow(row),然后使用该行来呈现单元格。

也许与:row.cells.map

此时,您可以根据单元格的内容执行不同的操作row.cells[0]

也许是这样的:

                  {(row.cells[0].value !== "Error" && row.cells.map(cell =>
                    {
                        return (
                            <TableCell {...cell.getCellProps({ className: cell.column.className })}>
                                {cell.render('Cell')}
                            </TableCell>
                        );
                    })) ||  <RedRow />}
Run Code Online (Sandbox Code Playgroud)