升级到 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. 更新导入
根据您使用的 Material UI 版本,您必须按如下方式更新导入
// 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. 移除旧版属性
item
和 zeroMinWidth
属性已在新版 Grid 中移除。您可以安全地移除它们
-<Grid item zeroMinWidth>
+<Grid>
3. 更新 size 属性
在 GridLegacy 组件中,size 属性的命名与主题的断点相对应。对于默认主题,这些属性是 xs
、sm
、md
、lg
和 xl
。
从 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. 选择加入旧版负边距
如果您使用 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} />;
您需要手动更新这些组件。