跳到內容
+

從 v5 遷移到 v6

本指南描述了從 v5 遷移資料格到 v6 所需的變更。

簡介

若要開始使用,請查看關於 MUI X v6 發佈的部落格文章

開始使用新版本

package.json 中,將資料格套件的版本變更為 ^6.0.0

-"@mui/x-data-grid": "^5.0.0",
+"@mui/x-data-grid": "^6.0.0",

由於 v6 是一個主要版本,因此它包含影響公開 API 的變更。 這些變更的目的是為了提高一致性、改善穩定性並為新功能騰出空間。 下面描述了從 v5 遷移到 v6 所需的步驟。

執行程式碼轉換 (codemods)

preset-safe 程式碼轉換將自動調整您的大部分程式碼,以適應 v6 中的重大變更。 您可以執行 v6.0.0/data-grid/preset-safe,僅以資料格為目標,或執行 v6.0.0/preset-safe,以日期和時間選擇器為目標。

您可以選擇 <path> 引數時,在特定檔案、資料夾或整個程式碼庫上執行它。

// Data Grid specific
npx @mui/x-codemod@latest v6.0.0/data-grid/preset-safe <path>
// Target Date and Time Pickers as well
npx @mui/x-codemod@latest v6.0.0/preset-safe <path>

preset-safe 程式碼轉換處理的重大變更,在螢幕右側的目錄中或在由其處理的特定點旁邊,以 ✅ 表情符號表示。

如果您已套用 v6.0.0/data-grid/preset-safe(或 v6.0.0/preset-safe)程式碼轉換,則您應該不需要對這些項目採取任何進一步的行動。 如果有不屬於程式碼轉換或需要一些手動工作的重大變更的特定部分,它將列在每個章節的末尾。

所有其他變更都必須手動處理。

重大變更

由於 v6 是一個主要版本,因此它包含一些影響公開 API 的變更。 這些變更的目的是為了提高一致性、改善穩定性並為新功能騰出空間。 下面描述了您需要進行的從 v5 遷移到 v6 的步驟。

✅ 已重新命名的 props

  • 為了避免與將為儲存格選取功能新增的 props 混淆,一些與列選取相關的 props 已重新命名為在其名稱中包含「row」。 重新命名的 props 如下

    舊名稱 新名稱
    selectionModel rowSelectionModel
    onSelectionModelChange onRowSelectionModelChange
    disableSelectionOnClick disableRowSelectionOnClick
    disableMultipleSelection disableMultipleRowSelection
    showCellRightBorder showCellVerticalBorder
    showColumnRightBorder showColumnVerticalBorder
    headerHeight columnHeaderHeight
  • rowSelectionModel(先前為 selectionModel)的對應類型已從 GridSelectionModel 重新命名為 GridRowSelectionModel

已移除的 props

  • 已移除 disableIgnoreModificationsIfProcessingProps prop,並且當 true 時的行為已納入為預設行為。 可以使用 apiRef.current.stopRowEditMode({ ignoreModifications: true })apiRef.current.stopCellEditMode({ ignoreModifications: true }) 來還原舊行為。
  • 已移除 onColumnVisibilityChange prop。 請改用 onColumnVisibilityModelChange
  • 已移除 components.Header 插槽。 請改用 components.Toolbarslots.toolbar 插槽。
  • ✅ 已移除 disableExtendRowFullWidth prop。 使用 showCellVerticalBordershowColumnVerticalBorder prop 來顯示或隱藏儲存格和標頭儲存格的右邊框。
  • 已移除 columnTypes prop。 關於自訂欄類型,請參閱自訂欄類型文件。
  • ✅ 已移除 onCellFocusOut prop。 請改用 slotProps.cell.onBlur
    <DataGrid
      slotProps={{
        cell: {
          onBlur: (event) => {
            const cellElement = event.currentTarget;
            const field = cellElement.getAttribute('data-field');
            const rowId = cell.parentElement.getAttribute('data-id');
          },
        },
      }}
    />
    
  • 已移除 erroronError props - 格線不再捕捉渲染期間的錯誤。 若要捕捉渲染期間發生的錯誤,請使用錯誤邊界。 也已移除 components.ErrorOverlay 插槽。

狀態存取

  • gridSelectionStateSelector 選取器已重新命名為 gridRowSelectionStateSelector
  • ✅ 已移除 allGridColumnsFieldsSelector 選取器。 請改用 gridColumnFieldsSelector
  • ✅ 已移除 allGridColumnsSelector 選取器。 請改用 gridColumnDefinitionsSelector
  • ✅ 已移除 visibleGridColumnsSelector 選取器。 請改用 gridVisibleColumnDefinitionsSelector
  • ✅ 已移除 filterableGridColumnsSelector 選取器。 請改用 gridFilterableColumnDefinitionsSelector
  • gridVisibleSortedRowIdsSelector 選取器已重新命名為 gridExpandedSortedRowIdsSelector
  • gridVisibleSortedRowEntriesSelector 選取器已重新命名為 gridExpandedSortedRowEntriesSelector
  • gridVisibleRowCountSelector 選取器已重新命名為 gridExpandedRowCountSelector
  • gridVisibleSortedTopLevelRowEntriesSelector 選取器已重新命名為 gridFilteredSortedTopLevelRowEntriesSelector
  • gridVisibleTopLevelRowCountSelector 選取器已重新命名為 gridFilteredTopLevelRowCountSelector
  • ✅ 已移除 getGridNumericColumnOperators 選取器。 請改用 getGridNumericOperators
  • 已移除 gridVisibleRowsSelector 選取器。 請改用 gridExpandedSortedRowIdsSelector
  • 已移除 gridColumnsSelector 選取器。 請改用更具體的格線欄選取器。
    -const { all, lookup, columnVisibilityModel } = gridColumnsSelector(apiRef);
    +const all = gridColumnFieldsSelector(apiRef);
    +const lookup = gridColumnLookupSelector(apiRef);
    +const columnVisibilityModel = gridColumnVisibilityModelSelector(apiRef);
    
  • 已移除 filterableGridColumnsIdsSelector 選取器。 請改用 gridFilterableColumnLookupSelector
    -const filterableFields = filterableGridColumnsIdsSelector(apiRef);
    +const lookup = gridFilterableColumnLookupSelector(apiRef);
    +const filterableFields = gridColumnFieldsSelector(apiRef).filter(field => lookup[field]);
    
  • 已移除 visibleGridColumnsLengthSelector 選取器。 請改用 gridVisibleColumnDefinitionsSelector
    -const visibleColumnsLength = visibleGridColumnsLengthSelector(apiRef);
    +const visibleColumnsLength = gridVisibleColumnDefinitionsSelector(apiRef).length;
    
  • 已移除 gridColumnsMetaSelector 選取器。 請改用 gridColumnsTotalWidthSelectorgridColumnPositionsSelector
    -const { totalWidth, positions } = gridColumnsMetaSelector(apiRef);
    +const totalWidth = gridColumnsTotalWidthSelector(apiRef);
    +const positions = gridColumnPositionsSelector(apiRef);
    
  • 已移除 gridRowGroupingStateSelector 選取器。
  • 已移除 gridFilterStateSelector 選取器。
  • 已移除 gridRowsStateSelector 選取器。
  • 已移除 gridSortingStateSelector 選取器。
  • 已移除 gridTotalHeaderHeightSelector 選取器。
  • 已移除 gridDensityRowHeightSelector 選取器。
  • 已移除 gridDensityHeaderHeightSelector 選取器。
  • 已移除 gridEditRowsStateSelector 選取器。
  • 已移除 apiRef.current.state.density.headerHeight 屬性。
  • 已移除 apiRef.current.state.density.rowHeight 屬性。

事件

  • selectionChange 事件已重新命名為 rowSelectionChange
  • rowsScroll 事件已重新命名為 scrollPositionChange
  • 已移除 columnVisibilityChange 事件。 請改用 columnVisibilityModelChange
  • 已移除 cellNavigationKeyDown 事件。 請使用 cellKeyDown 並檢查事件引數中提供的按鍵。
  • 已移除 columnHeaderNavigationKeyDown 事件。 請使用 columnHeaderKeyDown 並檢查事件引數中提供的按鍵。
  • cellKeyDown 事件也將針對在使用入口 (Portals) 的元件內發生的鍵盤事件觸發。 這特別會影響自訂編輯元件,在這些元件中,按下快捷鍵將觸發停止編輯常式。 例如,在入口內按下 Enter 將導致變更被儲存。 可以使用 onCellEditStop(或 onRowEditStop)prop 來還原舊行為。
    <DataGrid
      onCellEditStop={(params, event) => {
        if (params.reason !== GridCellEditStopReasons.enterKeyDown) {
          return;
        }
        // Check if the target is inside a Portal
        if (
          (event.target as any).nodeType === 1 &&
          !event.currentTarget.contains(event.target)
        ) {
          event.defaultMuiPrevented = true;
        }
      }}
    />
    
  • 已移除 componentError 事件。 請使用錯誤邊界來捕捉在渲染期間擲出的錯誤。
  • 已從事件詳細資訊中移除 GridCallbackDetails['api']。 請改用 useGridApiContextuseGridApiRef 傳回的 apiRef
  • cellFocusIncellFocusOut 事件現在是內部事件。 請改用 slotProps.cell.onFocusslotProps.cell.onBlur props。

  • 已移除 GridColDef['hide'] 屬性。 請改用 columnVisibilityModel

  • column.renderCellcolumn.renderEditCell 中傳回 null 現在會渲染一個空儲存格,而不是預設格式化的值。 若要回復為預設格式化的值,請傳回 undefined 而不是 null

     const renderCell = () => {
      if (condition) {
        return <CustomComponent />;
      }
    - return null;
    + return undefined;
     }
    
  • 現在僅當重新排序的欄放置在另一個位置時,才會呼叫 onColumnOrderChange prop 回呼。

  • valueOptions 是物件陣列時,singleSelect 欄類型現在具有傳回與選取值對應的 label 的預設值格式器。 因此,任何現有的值格式器將不再套用於個別選項,而僅套用於儲存格的文字。 建議將 valueOptions 遷移到物件陣列,以便能夠為每個值新增自訂標籤。 若要在儲存格處於編輯模式或篩選面板中時覆寫用於每個選項的標籤,以下元件現在支援 getOptionLabel prop

    • GridEditSingleSelectCell
    • GridFilterInputSingleSelect
    • GridFilterInputMultipleSingleSelect

    此 prop 接受一個回呼,該回呼使用來自 valueOptions 的項目呼叫,並且必須傳回用作新標籤的字串。

  • datedateTime 欄現在僅支援 Date 物件作為值。 若要剖析字串值,請使用 valueGetter

    <DataGrid
      columns={[
        {
          field: 'date',
          type: 'date',
          valueGetter: (params) => new Date(params.value),
        },
      ]}
    />
    

✅ 欄選單

  • 欄選單元件已重新命名或與新設計合併,以實現一致性和 API 改善,新元件如下

    舊名稱 新名稱
    GridFilterMenuItem GridColumnMenuFilterItem
    HideGridColMenuItem GridColumnMenuHideItem
    GridColumnsMenuItem GridColumnMenuColumnsItem
    SortGridMenuItems GridColumnMenuSortItem
    GridColumnPinningMenuItems GridColumnMenuPinningItem
    GridAggregationColumnMenuItem GridColumnMenuAggregationItem
    GridRowGroupingColumnMenuItemsGridRowGroupableColumnMenuItems GridColumnMenuGroupingItem
  • GridFilterItemProps 類型已重新命名為 GridColumnMenuItemProps

  • 傳遞到 GridColumnMenu 和欄選單項目的 Props columncurrentColumn 已重新命名為 colDef

    -function CustomColumnMenu({ column }) {
    -  if (column.field === 'name') {
    +function CustomColumnMenu({ colDef }) {
    +  if (colDef.field === 'name') {
         return <div>Custom column menu for name field</div>;
       }
       return (
         <div>
           <GridFilterMenuItem colDef={colDef} />
           <GridColumnMenuColumnsItem colDef={colDef} />
         </div>
       );
     }
    

  • 已移除 GridRowParams['getValue'] 屬性。 請改用 params.row
  • 已移除 GridCellParams['getValue'] 屬性。 請改用 params.row
  • GridCellParams['value'] 的預設類型已從 any 變更為 unknown
  • 已移除 GridActionsCellProps['api'] 屬性。 請改用 useGridApiContext 勾點以取得 apiRef
  • 已移除 GridActionsCellProps['getValue'] 屬性。 請改用 params.row
  • 已移除 GridFooterCellProps['getValue'] 屬性。 請改用 params.row
  • cellFocuscellTabIndexeditRowsState props 不再傳遞到 Row 插槽。 請改用 focusedCelltabbableCell props。 關於編輯狀態,請使用 API 方法。
     function CustomRow(props) {
    -  const focusedField = props.cellFocus.field;
    -  const tabIndex = props.cellTabIndex.field && cellMode === 'view' ? 0 : 1;
    +  const focusedField = props.focusedCell;
    +  const tabIndex = props.tabbableCell === column.field ? 0 : 1;
    
  • 更新rows prop 或呼叫 apiRef.current.setRows 現在將移除格線的展開狀態,因為這些方法旨在替換列。 關於部分列更新,請改用apiRef.current.updateRows 方法。

分頁

  • 已移除 pagepageSize props 及其各自的事件處理常式 onPageChangeonPageSizeChange。 請改用 paginationModelonPaginationModelChange

     <DataGrid
    -  page={page}
    -  pageSize={pageSize}
    -  onPageChange={handlePageChange}
    -  onPageSizeChange={handlePageSizeChange}
    +  paginationModel={{ page, pageSize }}
    +  onPaginationModelChange={(paginationModel) => handlePaginationModelChange(paginationModel)}
     />
    
  • 也已移除屬性 initialState.pagination.pageinitialState.pagination.pageSize。 請改用 initialState.pagination.paginationModel

    -initialState={{ pagination: { page: 1, pageSize: 10 } }}
    +initialState={{ pagination: { paginationModel: { page: 1, pageSize: 10 } } }}
    
  • rowsPerPageOptions prop 已重新命名為 pageSizeOptions

    -<DataGrid rowsPerPageOptions={[10, 20, 50]} />
    +<DataGrid pageSizeOptions={[10, 20, 50]} />
    

apiRef 方法

  • ✅ 已移除 apiRef.current.getRowIndex 方法。 請改用 apiRef.current.getRowIndexRelativeToVisibleRows

  • apiRef.current.setFilterLinkOperator 方法已重新命名為 apiRef.current.setFilterLogicOperator

  • 已移除 apiRef.current.updateColumn 方法。 請改用 apiRef.current.updateColumns

    -apiRef.current.updateColumn({ field: 'name', width: 100 });
    +apiRef.current.updateColumns([{ field: 'name', width: 100 }]);
    
  • 已移除 apiRef.current.getColumnsMeta 方法。 請改用 gridColumnsTotalWidthSelectorgridColumnPositionsSelector 選取器。

    -const { totalWidth, positions } = apiRef.current.getColumnsMeta();
    +const totalWidth = gridColumnsTotalWidthSelector(apiRef);
    +const positions = gridColumnPositionsSelector(apiRef);
    
  • 已變更 apiRef.current.setDensity 簽章。 它僅接受 density: GridDensity 作為單一參數。

  • 已移除 apiRef.current.getVisibleRowModels 方法。 請改用 gridExpandedSortedRowEntriesSelector 選取器。

  • 已移除 apiRef.current.showError 方法。 格線不再處理錯誤的 UI。

  • 已移除一些內部未記載的 apiRef 方法和屬性。

    如果您不使用未記載的屬性 - 您可以略過下面的列表。 否則,請檢查列表,如果 apiRef 中缺少某些內容,請開啟問題

    已移除的未記載方法和屬性列表
    getLogger
    windowRef
    footerRef
    headerRef
    columnHeadersElementRef
    columnHeadersContainerElementRef
    unstable_caches
    unstable_eventManager
    unstable_requestPipeProcessorsApplication
    unstable_registerPipeProcessor
    unstable_registerPipeApplier
    unstable_storeDetailPanelHeight
    unstable_detailPanelHasAutoHeight
    unstable_calculateColSpan
    unstable_rowHasAutoHeight
    unstable_getLastMeasuredRowIndex
    unstable_getViewportPageSize
    unstable_updateGridDimensionsRef
    unstable_getRenderContext
    unstable_registerStrategyProcessor
    unstable_applyStrategyProcessor
    unstable_getActiveStrategy
    unstable_setStrategyAvailability
    unstable_setCellEditingEditCellValue
    unstable_getRowWithUpdatedValuesFromCellEditing
    unstable_setRowEditingEditCellValue
    unstable_getRowWithUpdatedValuesFromRowEditing
    unstable_runPendingEditCellValueMutation
    unstable_moveFocusToRelativeCell
    unstable_updateControlState
    unstable_registerControlState

篩選

  • GridFilterItem['columnField'] 已重新命名為 GridFilterItem['field']
  • GridFilterItem['operatorValue'] 已重新命名為 GridFilterItem['operator']
  • 現在需要 GridFilterItem['operator']
  • GridFilterInputValue 元件不能再與 singleSelect 欄一起使用。 請改用 GridFilterInputSingleSelect
  • GridLinkOperator 列舉已重新命名為 GridLogicOperator
  • GridFilterModel['linkOperator'] 類型已重新命名為 GridFilterModel['logicOperator']
  • GridFilterFormGridFilterPanel 元件的 linkOperators prop 已重新命名為 logicOperators
  • GridFilterForm 元件的 linkOperatorInputProps prop 已重新命名為 logicOperatorInputProps
  • GridFilterForm 元件中的 filterFormProps.linkOperatorInputProps prop 已重新命名為 filterFormProps.logicOperatorInputProps
  • GridLocaleText['filterPanelLinkOperator'] 屬性已重新命名為 GridLocaleText['filterPanelLogicOperator']

編輯

  • ✅ 預設啟用的編輯 API 已替換為新的 API,該 API 包含對伺服器端持久性、驗證和自訂的更好支援。 此新的編輯功能已在 v5 中以 newEditingApi 實驗性標誌提供。 在 v6 中,可以移除此標誌。
     <DataGrid
    -  experimentalFeatures={{ newEditingApi: true }}
     />
    
  • ✅ 彙總和列釘選不再是實驗性功能。 現在可以移除標誌 experimentalFeatures.aggregationexperimentalFeatures.rowPinning
     <DataGridPremium
    -  experimentalFeatures={{
    -   aggregation: true,
    -   rowPinning: true,
    -  }}
     />
    
  • 已移除 editCellPropsChange 事件。 如果您仍然需要它,請提交新的問題,以便我們可以提出替代方案。
  • 已移除 cellEditCommit 事件,並且可以使用 processRowUpdate prop 代替。 更多資訊,請查看關於該主題的文件章節。
  • 已移除 editRowsModelonEditRowsModelChange props。 可以使用 cellModesModelrowModesModel props 來達到相同的目標。
  • 已移除 GridEditRowsModel 類型。
  • 已移除以下 API 方法
    • 使用 apiRef.current.stopCellEditMode 來替換 apiRef.current.commitCellChange
    • 使用 apiRef.current.startCellEditMode 來替換 apiRef.current.setCellMode(id, field, 'edit')
    • 使用 apiRef.current.stopRowEditMode 來替換 apiRef.current.commitRowChange
    • 使用 apiRef.current.startRowMode 來替換 apiRef.current.setRowMode(id, 'edit')
    • 使用 cellModesModelrowModesModel props 來替換 apiRef.current.setEditRowsModel

其他匯出

  • 已移除 useGridApi 勾點。 請改用 apiRef.current

  • 已移除 useGridState 勾點。 請改用 apiRef.current.stateapiRef.current.setStateapiRef.current.forceUpdate

  • 已移除 getGridColDef 公用程式函式。

  • 已移除 GridColumns 類型。 請改用 GridColDef[]

  • 已移除 GridActionsColDef 介面。 請改用 GridColDef

  • 已移除 GridEnrichedColDef 類型。 請改用 GridColDef

  • 已移除 GridStateColDef 類型。

  • 已移除 GridDensityTypes 列舉。 請改用 GridDensity 類型。

    如果您使用它來鍵入 searchPredicate - 請改用 GridColumnsPanelProps['searchPredicate']

    如果您使用它來鍵入 getApplyFilterFn - 請改用 GridFilterOperator['getApplyFilterFn']

  • 已移除 GridHeaderPlaceholder 元件。

  • 已移除 GridValueGetterFullParams 類型。

  • 已移除 GridSortModelParams 介面。

  • 已移除 GridApiRef 類型。 請改用 React.MutableRefObject<GridApi>

  • 已移除 GridCellValue 類型。 請改用 any 或傳遞到大多數介面的 V 泛型。

  • 已移除 GridRowData 類型。 請改用 GridRowModel

  • filterPanelOperators 翻譯鍵已重新命名為 filterPanelOperator

  • 已移除 MAX_PAGE_SIZE 常數。

  • 已移除 DATA_GRID_DEFAULT_SLOTS_COMPONENTS 匯出。

  • 已移除 useGridScrollFn 勾點。

  • 已變更 GridCellParams 介面。 列泛型現在位於儲存格泛型之前。

    -extends GridCellParams<V, R, F, N> {
    +extends GridCellParams<R, V, F, N> {
    

    這表示在您已擁有的引數之前,需要提供 2 個泛型引數的值。

    -renderCell: (params: GridRenderCellParams<number>) => {
    +renderCell: (params: GridRenderCellParams<any, number>) => {
    
  • 已移除 GridErrorOverlay 元件。

  • GridRowScrollEndParams["virtualRowsCount"] 參數已重新命名為 GridRowScrollEndParams["visibleRowsCount"]

  • 已移除 GridCellIdentifier 類型。 請改用 GridCellCoordinates

✅ CSS 類別

  • 已移除或重新命名一些 CSS 類別

    MUI X v5 類別 MUI X v6 類別 注意
    .MuiDataGrid-withBorder .MuiDataGrid-withBorderColor 該類別僅設定 border-color CSS 屬性
    .MuiDataGrid-filterFormLinkOperatorInput .MuiDataGrid-filterFormLogicOperatorInput

從公開 API 中移除

  • 已移除 getGridSingleSelectQuickFilterFn 函式。 您可以複製舊函式並將其傳遞到 singleSelect 欄定義的 getApplyQuickFilterFn 屬性。

components 重新命名為 slots(選用)

componentscomponentsProps props 正在分別重新命名為 slotsslotProps props。 這是 MUI 維護的所有不同程式庫之間正在進行的緩慢而持續的努力。 為了順利過渡,資料格同時支援已棄用的 components props 和新的 slots props。

如果您想使用新的 API 並且不想看到已棄用 prop 的使用情況,請考慮執行 rename-components-to-slots 程式碼轉換來處理 prop 重新命名。

npx @mui/x-codemod@latest v6.0.0/data-grid/rename-components-to-slots <path>

查看 RFC 以獲取更多資訊。