Material UI React TypeScript:如何向GridToolbar传递选中行数据
问题描述
我想在GridHeader中添加选中行后的操作,参考了MUI官方的受控选择和列可见性面板相关教程。这应该是个很普遍的需求,但选中单行或多行后,没法把选中结果数据传递给GridToolbar子组件,这个组件好像不支持属性传递。
以下是示例代码:
export default function App(props: any){ const {rows, columns} = props; const [selectionModel, setSelectionModel] = useState<GridSelectionModel>([]); return ( <DataGrid components={{ Toolbar: DataToolbar }} onSelectionModelChange={(newSelectionModel) => { setSelectionModel(newSelectionModel); }} selectionModel={selectionModel} {...others} /> ); } function DataToolbar (){ return ( <GridToolbarContainer> <Auctions /> <GridToolbarQuickFilter /> <GridToolbarColumnsButton /> <GridToolbarDensitySelector /> </GridToolbarContainer> ); } function Auctions (){ const apiRef = useGridApiContext(); const [selected, setSelected] = useState(false); const handleSelected: GridEventListener<'rowSelectionCheckboxChange'> = ( params, event, details) => { //Processing Event setSelected(!selected); }; useGridApiEventHandler(apiRef, 'rowSelectionCheckboxChange', handleSelected); return ( <Fragment> <IconButton disabled={!selected}><DeleteIcon color={selected? "error" : "disabled"} /></IconButton> </Fragment> ); }
解决方案
方案一:通过Toolbar props传递选中状态
MUI DataGrid会自动将自身的props(包括selectionModel)传递给自定义Toolbar组件,你可以直接接收并传递给子组件:
export default function App(props: any){ const {rows, columns} = props; const [selectionModel, setSelectionModel] = useState<GridSelectionModel>([]); return ( <DataGrid components={{ Toolbar: DataToolbar }} onSelectionModelChange={(newSelectionModel) => { setSelectionModel(newSelectionModel); }} selectionModel={selectionModel} {...others} /> ); } // 接收DataGrid传入的selectionModel并传递给Auctions function DataToolbar ({ selectionModel }: { selectionModel: GridSelectionModel }){ return ( <GridToolbarContainer> <Auctions selectionModel={selectionModel} /> <GridToolbarQuickFilter /> <GridToolbarColumnsButton /> <GridToolbarDensitySelector /> </GridToolbarContainer> ); } // 直接使用传入的selectionModel判断选中状态 function Auctions ({ selectionModel }: { selectionModel: GridSelectionModel }){ const hasSelectedRows = selectionModel.length > 0; return ( <Fragment> <IconButton disabled={!hasSelectedRows}> <DeleteIcon color={hasSelectedRows ? "error" : "disabled"} /> </IconButton> </Fragment> ); }
方案二:通过Grid API上下文获取选中状态
无需手动传递props,直接在子组件中通过useGridApiContext获取网格实例,实时获取选中行数据:
function Auctions (){ const apiRef = useGridApiContext(); // 获取当前选中的行ID集合 const selectionModel = apiRef.current.getSelectionModel(); const hasSelectedRows = selectionModel.length > 0; return ( <Fragment> <IconButton disabled={!hasSelectedRows}> <DeleteIcon color={hasSelectedRows ? "error" : "disabled"} /> </IconButton> </Fragment> ); }
注意:使用此方案时,确保Auctions组件位于DataGrid的上下文范围内(即作为自定义Toolbar的一部分),否则无法获取到有效的apiRef。
内容的提问来源于stack exchange,提问作者HappyKoala
相关产品推荐
相关产品推荐

