我一直在关注 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/>
}
...
}
}
是否可以将自定义样式应用于包含单元格的行?我想必须将 Prop 传递给行,但我根本不清楚如何做到这一点。任何指针将不胜感激。
最佳答案
对于任何在这个问题上绊倒的人,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 组件中,你传递你选择的行的任何 Prop (比如, 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>
);
}
关于reactjs - 如何将 Prop 传递给 react 表中的行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63588421/