简体   繁体   English

使用自定义复选框实现Ag-Grid行选择

[英]Implementing ag-Grid row selection with custom checkbox

I have the following ColDef for my ag-Grid table: 我的ag-Grid表具有以下ColDef

const checkboxRenderer: React.SFC<ICellRendererParams> = params => {
  const checked = find(this.state.selectedOptions, x => x.id === params.data.id) != null;
  return (
    <div className="custom__cb">
      <input type="checkbox" checked={checked} />
      <label>
        <span className="custom__cb__label-text">{params.value}</span>
      </label>
    </div>
  );
};

const columnDef: ColDef = 
    colDef.field = 'id';
    colDef.cellRendererFramework = checkboxRenderer;
}

I've defined my ag-Grid table like this: 我已经这样定义了ag-Grid表:

onSelectionChanged = (e: SelectionChangedEvent) => {
  const { api } = e;
  if (api) {
    const selectedOptions = api.getSelectedRows();
    this.setState({ selectedOptions });
  }
};

onRowSelected = (e: RowSelectedEvent) => {
  const isAlreadySelected = find(this.state.selectedOptions, x => x.id === e.data.id) != null;
  if (isAlreadySelected) {
    this.setState({ selectedOptions: this.state.selectedOptions.filter(x => x.id !== e.data.id) });
  } else {
    this.setState({ selectedOptions: [...this.state.selectedOptions, e.data] });
  }
};

<AgGridReact
  columnDefs={columnDefs}
  rowData={options}
  onSelectionChanged={this.onSelectionChanged}
  onRowSelected={this.onRowSelected}
  rowSelection="multiple"
/>

This renders the correct custom checkbox and also sets selectedOptions in my component state correctly when a row is selected. 这将呈现正确的自定义复选框,并且在选择一行时还可以将组件中的selectedOptions设置为正确。 The problem is that my custom checkbox does not reflect the correct checked status. 问题是我的自定义复选框未反映正确的选中状态。 It is always unchecked. 始终未选中。 It doesn't look like checkboxRenderer is re-rendering when my state is changed. 更改我的状态后,看起来checkboxRenderer并没有重新呈现。

How can I implement a custom row selection checkbox that correctly reflects the checked state? 如何实现自定义行选择复选框以正确反映选中状态?

I'm uncertain this pertains to your issue, but the following were keys to getting AgGridReact to update upon state change: 我不确定这与您的问题有关,但是以下是使AgGridReact在状态更改时进行更新的关键:

On the <AgGridReact component, use onGridReady property instead of setting data and also set deltaRowDataMode={true} <AgGridReact组件上,使用onGridReady属性而不是设置数据,并且还要设置deltaRowDataMode={true}

In componentDidUpdate React component event, selectively (only when row data changes) reset row data via this.gridApi.setRowData(rowData) componentDidUpdate React组件事件中,有选择地(仅当行数据更改时)通过this.gridApi.setRowData(rowData)重置行数据

Those changes were key to making the grid update while maintaining the grid's state. 这些更改是在保持网格状态的同时更新网格的关键。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM