迭代反应 ag-grid 的特定行

问题描述

我得到了一个 ag-grid,其中一个按钮呈现在一个专用列中(意味着每一行在该列下方的一侧都有一个按钮)。我是这样做的:

const columnDeFinition = [
                          {headerName: '',cellRenderer: 'editButton'},{headerName: "Key",field: "Key"},{headerName: "Value",field: "Value"}];

const overlayParams = {
  frameworkComponents: {
                        editButton: EditMagnifierButton,//EditMagnifierButton is a react functional component which renders a button
                       }
return (
 <Ag-Grid-React
     rowData={myRowData}
     columnDefs={columnDeFinition} 
     {...overlayParams} />
);

我想知道如何遍历用户单击按钮的行并获取该行每一列中的所有值,以便我可以将它们作为道具传递给另一个组件。

EditMagnifierButton

const EditMagnifier = (props) =>
{
    return (
        <IconButton iconSvg={search} />
    )
}

解决方法

如 ag-Grid 文档中所述,ag-Grid 将一些默认道具传递给每个单元格渲染器,这些道具的格式为 ICellRendererParams

interface ICellRendererParams {
    value: any,// value to be rendered
    valueFormatted: any,// value to be rendered formatted
    getValue: () => any,// convenience function to get most recent up to date value
    setValue: (value: any) => void,// convenience to set the value
    formatValue: (value: any) => any,// convenience to format a value using the column's formatter
    data: any,// the row's data
    node: RowNode,// row node
    colDef: ColDef,// the cell's column definition
    column: Column,// the cell's column
    rowIndex: number,// the current index of the row (this changes after filter and sort)
    api: GridApi,// the grid API
    eGridCell: HTMLElement,// the grid's cell,a DOM div element
    eParentOfValue: HTMLElement,// the parent DOM item for the cell renderer,same as eGridCell unless using checkbox selection
    columnApi: ColumnApi,// grid column API
    context: any,// the grid's context
    refreshCell: () => void // convenience function to refresh the cell
}

可以在下面找到详细信息, https://www.ag-grid.com/javascript-grid-cell-rendering-components/#cell-renderer-component

因此,有一个名为 data 的属性指向 rowData,该属性指向存在单元格渲染器的索引(在本例中为单击的索引)。

所以你的单元渲染器可以直接使用这个道具作为props.data

/* Here the props will point to ICellRendererParams */
const EditMagnifier = (props) =>
{

    const printRowData = (event) => {
      /* This will give you the complete row data for the clicked row*/
      console.log(props.data);
    }
    
    return (
        <IconButton iconSvg={search} onClick={printRowData}/>
    )
}