要限制可选行数,可以使用gridOptions属性的rowSelection属性。将rowSelection设置为“multiple”以允许多行选择。然后,使用gridOptions.onSelectionChanged事件来捕获当前选择的行数。最后,使用gridApi.deselectAll()方法来取消选择所有行。
以下是代码示例:
import React, { Component } from 'react';
import { AgGridReact } from 'ag-grid-react';
class MyGrid extends Component {
constructor(props) {
super(props);
this.state = {
rowData: [],
selectedRow: null
};
this.gridOptions = {
rowSelection: 'multiple',
onSelectionChanged: this.onSelectionChanged.bind(this)
};
this.columnDefs = [
{headerName: "Make", field: "make"},
{headerName: "Model", field: "model"},
{headerName: "Price", field: "price"}
];
}
componentDidMount() {
fetch('https://api.myjson.com/bins/15psn9')
.then(result => result.json())
.then(rowData => this.setState({rowData}));
}
onSelectionChanged() {
const { api } = this.gridOptions;
const selectedRows = api.getSelectedRows();
if (selectedRows.length > 3) {
api.deselectAll();
alert("不能选择超过3行!");
} else {
this.setState({selectedRow: selectedRows[0]});
}
}
render() {
const { rowData, selectedRow } = this.state;
return (
{selectedRow ? (
Selected: {selectedRow.make} {selectedRow.model}
) : null}
);
}
}
export default MyGrid;