如何将自定义道具从 App 传递到单元格以进行 react-table v7?

Posted

技术标签:

【中文标题】如何将自定义道具从 App 传递到单元格以进行 react-table v7?【英文标题】:How to pass a custom prop from App to cell for react-table v7? 【发布时间】:2020-06-04 19:19:57 【问题描述】:

这就是我渲染表格主体的方式:

        <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 功能。

我该怎么做?

谢谢。

【问题讨论】:

【参考方案1】:

您也可以在 CellCell 的基础上执行此操作,方法是将 props 对象直接传递给渲染函数:

...
  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 />
      );
    ,
  

【讨论】:

主键就在这里。谢谢,因为我在查看文档后并不清楚这个概念 很好的答案,谢谢。我将当前行值作为; cell.render("Cell", status: row.original.status ) 我希望这既是正确的方式,又对您有益。 "react-table": "^7.7.0"【参考方案2】:

您可以通过使用传递给Cell 组件的column 属性来实现:

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

【讨论】:

以上是关于如何将自定义道具从 App 传递到单元格以进行 react-table v7?的主要内容,如果未能解决你的问题,请参考以下文章

如何将自定义信息从 App Engine Authenticator 传递到 Endpoint?

如何将自定义道具传递给 QueryRenderer 渲染函数?

如何使用 Material UI 和 TypeScript 将自定义道具传递给样式化组件?

将自定义道具传递给 TypeScript 中的 Redux 表单字段

将自定义单元格从一个视图控制器传递到另一个视图控制器

如何将自定义数据从ui-router中的视图传递到某个状态?