資料網格 - 自訂插槽與子組件
了解如何覆寫網格的各個部分。
與資料網格互動
網格公開了兩個 Hook,以協助您在覆寫組件插槽時訪問資料網格資料。
它們可以如下使用
function CustomPagination() {
const apiRef = useGridApiContext();
const paginationModel = useGridSelector(apiRef, gridPaginationModelSelector);
const pageCount = useGridSelector(apiRef, gridPageCountSelector);
return (
<Pagination
count={pageCount}
page={paginationModel.page + 1}
onChange={(event, value) => apiRef.current.setPage(value - 1)}
/>
);
}
組件插槽
欄面板
在以下示範中,欄面板已替換為自訂組件,該組件將欄組表示為巢狀列表。
欄選單
如上所述,欄選單是一個組件插槽,可以輕鬆地重新組成並在每個欄上自訂,如下面的示範所示。
工具列
若要啟用工具列,您需要將 toolbar: GridToolbar
新增至 Data Grid slots
屬性。此示範展示了如何實現這一點。
您也可以組成自己的工具列。工具列中的每個按鈕都使用工具提示組件包裝。為了覆寫與工具列按鈕對應的某些屬性,您可以使用 slotProps
屬性。
以下示範顯示如何覆寫密度選擇器的工具提示標題和匯出按鈕的變體。
function CustomToolbar() {
return (
<GridToolbarContainer>
<GridToolbarColumnsButton />
<GridToolbarFilterButton />
<GridToolbarDensitySelector
slotProps={{ tooltip: { title: 'Change density' } }}
/>
<Box sx={{ flexGrow: 1 }} />
<GridToolbarExport
slotProps={{
tooltip: { title: 'Export data' },
button: { variant: 'outlined' },
}}
/>
</GridToolbarContainer>
);
}
頁尾
網格公開了屬性以隱藏 UI 的特定元素
hideFooter
:若為true
,則會隱藏頁尾組件。hideFooterRowCount
:若為true
,則會隱藏頁尾中的列數。hideFooterSelectedRowCount
:若為true
,則會隱藏頁尾中選取的列數。hideFooterPagination
:若為true
,則會隱藏頁尾中的分頁組件。
分頁
預設分頁組件匯出為 GridPagination
。此組件是 TablePagination 組件的擴展,它呈現頁面大小控制項、頁面中的列數以及前往上一頁和下一頁的按鈕。您可以完全替換分頁組件或重複使用預設組件。
下一個示範重複使用了 GridPagination
,但將上一頁和下一頁按鈕替換為 Pagination,後者為每個頁面呈現一個專用按鈕。
儲存格
以下示範使用 slotProps.cell
屬性來監聽儲存格發出的特定事件。嘗試將滑鼠懸停在儲存格上,它應該會顯示每個儲存格具有的字元數。
圖示
與任何組件插槽一樣,每個圖示都可以自訂。但是,尚無法將 slotProps
與圖示一起使用。
覆蓋層
請參閱覆蓋層文件,了解如何自訂 loadingOverlay
、noRowsOverlay
和 noResultsOverlay
。
具有 TypeScript 的自訂插槽屬性
如果自訂組件需要其他屬性才能正常運作,TypeScript 可能會拋出類型錯誤。若要解決這些類型錯誤,請使用模組擴充來增強屬性介面。
可覆寫介面的命名使用如下模式
`${slotNameInPascalCase}PropsOverrides`;
例如,對於 columnMenu
插槽,介面名稱將為 ColumnMenuPropsOverrides
。
此檔案列出了可用於擴充的每個插槽的所有介面。
// augment the props for the toolbar slot
declare module '@mui/x-data-grid' {
interface ToolbarPropsOverrides {
someCustomString: string;
someCustomNumber: number;
}
}
<DataGrid
slots={{
// custom component passed to the toolbar slot
toolbar: CustomGridToolbar,
}}
slotProps={{
toolbar: {
// props used by CustomGridToolbar
someCustomString: 'Hello',
someCustomNumber: 42,
},
}}
/>;
下面的示範顯示如何使用 slotProps
屬性和模組擴充將新屬性 status
傳遞到 footer
插槽。