问题描述: 在使用ag-grid和React的过程中,当使用checkboxSelection选项时,状态不会更新。
解决方法:
示例代码:
import React, { Component } from 'react';
import { AgGridReact } from 'ag-grid-react';
import 'ag-grid-community/dist/styles/ag-grid.css';
import 'ag-grid-community/dist/styles/ag-theme-alpine.css';
class AgGridExample extends Component {
constructor(props) {
super(props);
this.state = {
selectedRows: [],
columnDefs: [
{ checkboxSelection: true, headerCheckboxSelection: true },
{ headerName: 'Make', field: 'make' },
{ headerName: 'Model', field: 'model' },
{ headerName: 'Price', field: 'price' }
],
rowData: [
{ make: 'Toyota', model: 'Celica', price: 35000 },
{ make: 'Ford', model: 'Mondeo', price: 32000 },
{ make: 'Porsche', model: 'Boxster', price: 72000 }
]
};
}
onGridReady = (params) => {
this.gridApi = params.api;
this.gridColumnApi = params.columnApi;
};
onSelectionChanged = () => {
const selectedRows = this.gridApi.getSelectedRows();
this.setState({ selectedRows });
};
render() {
return (
);
}
}
export default AgGridExample;
在上面的示例代码中,我们添加了一个名为"selectedRows"的状态属性,并在onSelectionChanged事件处理程序中更新该属性。这样,当用户选择或取消选择行时,selectedRows属性会相应地更新。