【问题标题】:How to pass props to row in react-table如何将道具传递到反应表中的行
【发布时间】:2020-12-14 17:02:35
【问题描述】:
【问题讨论】:
标签:
reactjs
react-table
react-table-v7
【解决方案1】:
对于遇到此问题的任何人,react-table 库的作者已在此处回答了此问题 — https://spectrum.chat/react-table/general/v7-row-getrowprops-how-to-pass-custom-props-to-the-row~ff772376-0696-49d6-b259-36ef4e558821
在您的 Table 组件中,您可以为行传递您选择的任何道具(例如,rowProps)——
<Table
columns={columns}
data={data}
rowProps={row => ({
onClick: () => alert(JSON.stringify(row.values)),
style: {
cursor: "pointer"
}
})}
/>
然后实际使用它-
function Table({ columns, data, rowProps = () => ({}) }) {
// Use the state and functions returned from useTable to build your UI
const { getTableProps, headerGroups, rows, prepareRow } = useTable({
columns,
data
});
// Render the UI for your table
return (
<table {...getTableProps()}>
<thead>
{headerGroups.map(headerGroup => (
<tr {...headerGroup.getHeaderGroupProps()}>
{headerGroup.headers.map(column => (
<th {...column.getHeaderProps()}>{column.render("Header")}</th>
))}
</tr>
))}
</thead>
<tbody>
{rows.map(
(row, i) =>
prepareRow(row) || (
<tr {...row.getRowProps(rowProps(row))}>
{row.cells.map(cell => {
return (
<td {...cell.getCellProps()}>{cell.render("Cell")}</td>
);
})}
</tr>
)
)}
</tbody>
</table>
);
}
【解决方案2】:
目前您正在为列定义应用样式。
为了将样式应用于整个行。 (例如,如果 value == "Error",则将整行设为红色),我会在您的表格 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 />}