这是我渲染表格主体的方式:
<tbody {...getTableBodyProps()}>
{rows.map((row, i) => {
prepareRow(row);
return (
<Row {...row.getRowProps()}>
{row.cells.map((cell) => {
// return <td {...cell.getCellProps()}>{cell.render("Cell")}</td>;
return cell.render("Cell");
})}
</Row>
);
})}
</tbody>
这是我设置列的方式。我为每个单元创建了唯一的组件。
[
{
Header: "Main Header",
Footer: "Foot",
columns: [
{
Header: "Code",
accessor: "NominalCode",
Cell: (props) => {
return <CodeCell>{props.cell.value}</CodeCell>;
},
Footer: () => {
return <FooterTotalCell>Total</FooterTotalCell>;
}
},
{
Header: "Description",
accessor: "Description",
Cell: (props) => {
return (
<DescriptionCell country={props.row.values.Currency}>
{String(props.cell.value)}
</DescriptionCell>
);
},
Footer: () => {
return <td />;
}
}
]
我想将功能作为道具从我的主App.jsx文件传递到DescriptionCell
组件。此功能将用于在DescriptionCell
内部执行一些onClick功能。
我该怎么做?
谢谢。
答案 0 :(得分:4)
您还可以通过将props对象直接传递到render函数,以Cell
到Cell
的方式执行此操作:
...
{rows.cells.map(cell => cell.render('Cell', { test: 'this is a test'}))}
...
然后在您的列定义中
columns: [
...
{
Cell: (props) => {
console.log(props.test) // the value is 'this is a test'
return (
<CustomComponent test={props.test} />
);
},
}
答案 1 :(得分:2)
您可以使用传递给column
组件的Cell
道具来做到这一点:
columns: [
...
{
Header: "Description",
accessor: "Description",
onClick: () => { alert('click!'); },
Cell: (props) => {
return (
<DescriptionCell onClick={props.column.onClick} country={props.row.values.Currency}>
{String(props.cell.value)}
</DescriptionCell>
);
},
}
或者,如果您的函数可能被其他许多单元使用(例如更新后端),则可以将该函数传递给主要的Table
组件,如以下示例所示:https://github.com/tannerlinsley/react-table/blob/master/examples/kitchen-sink-controlled/src/App.js#L622