跳到內容
+

升級至 Grid v2

本指南說明如何以及為何從 GridLegacy 元件遷移到 Grid 元件。

Grid 元件版本

在 Material UI v7 中,GridLegacy 元件已被棄用,並由 Grid 取代,後者提供了幾個新功能,以及開發者體驗的顯著改進。本指南說明如何從 GridLegacy 升級到 Grid,並包含 Material UI v5、v6 和 v7 的詳細資訊。

為何您應該升級

Grid 相較於 GridLegacy 提供了以下改進

  • 它使用 CSS 變數,從類別選擇器中移除 CSS 特異性。您可以使用 sx 屬性來控制您想要的任何樣式。
  • 所有 grid 都被視為 item,無需指定 item 屬性。
  • offset 功能為您提供更大的定位彈性。
  • 巢狀 grid 現在沒有深度限制。
  • 它的實作不使用負邊距,因此它不會像 GridLegacy 一樣溢出

如何升級

先決條件

在繼續升級之前

  • 您必須使用 Material UI v5+。
  • 如果您正在升級您的 Material UI 版本,您應該先完成該升級。

1. 更新 import

根據您使用的 Material UI 版本,您必須如下更新 import

// The legacy Grid component is named GridLegacy
-import Grid from '@mui/material/GridLegacy';

// The updated Grid component is named Grid
+import Grid from '@mui/material/Grid';

2. 移除 legacy 屬性

更新後的 Grid 中已移除 itemzeroMinWidth 屬性。您可以安全地移除它們

-<Grid item zeroMinWidth>
+<Grid>

3. 更新 size 屬性

在 GridLegacy 元件中,size 屬性的命名與主題的斷點相對應。對於預設主題,這些是 xssmmdlgxl

從 Material UI v6 開始,這些屬性在更新後的 Grid 上重新命名為 size

 <Grid
-  xs={12}
-  sm={6}
+  size={{ xs: 12, sm: 6 }}
 >

如果所有斷點的 size 都相同,則可以使用單個值

-<Grid xs={6}>
+<Grid size={6}>

此外,size 屬性的 true 值已重新命名為 "grow"

-<Grid xs>
+<Grid size="grow">

您可以使用以下 codemod 來更新 size 屬性

npx @mui/codemod@next v7.0.0/grid-props <path/to/folder>

4. 選擇加入 legacy 負邊距

如果您使用 Material UI v5 並想要套用類似於 GridLegacy 的負邊距,請在 grid 容器上指定 disableEqualOverflow={true}。若要套用至所有 grid,請將預設屬性新增至主題

import { createTheme, ThemeProvider } from '@mui/material/styles';
import Grid from '@mui/material/Unstable_Grid2';

const theme = createTheme({
  components: {
    MuiGrid2: {
      defaultProps: {
        // all grids under this theme will apply
        // negative margin on the top and left sides.
        disableEqualOverflow: true,
      },
    },
  },
});

function Demo() {
  return (
    <ThemeProvider theme={theme}>
      <Grid container>...grids</Grid>
    </ThemeProvider>
  );
}

常見問題

欄方向

GridLegacy更新後的 Grid 上,不支援使用 direction="column"direction="column-reverse"。如果您的版面配置使用具有這些值的 GridLegacy,當您切換到更新後的 Grid 時,可能會中斷。如果您需要垂直版面配置,請依照 Grid 文件中的指示。

容器寬度

更新後的 Grid 元件預設不會擴展到容器的完整寬度。如果您需要 grid 擴展到完整寬度,可以使用 sx 屬性

-<GridLegacy container>
+<Grid container sx={{ width: '100%' }}>

 // alternatively, if the Grid's parent is a flex container:
-<GridLegacy container>
+<Grid container sx={{ flexGrow: 1 }}>

Codemod 未涵蓋包裝的 Grid 元件

提供的 codemod 不會涵蓋包裝在其他元件或樣式中的 Grid 元件

// The codemod won't cover StyledGrid
const StyledGrid = styled(Grid)({
  // styles
});

// The codemod won't cover WrappedGrid
const WrappedGrid = (props) => <Grid {...props} />;

您需要手動更新這些元件。

文件頁面