Material UI 响应式网格方向

Material UI responsive grid direction

我希望容器方向为 md 尺寸屏幕上方的“行”和 md 尺寸屏幕下方的“列”? 我该如何实施?

<Grid container direction = "row"(in large screens)/direction = "column"(in small screens)>

我试过这个。

<Grid container classes={gridDirection}>

 gridDirection: {
    direction = "row",
    [theme.breakpoints.down('md')]: {
      direction = "column",
    },
  }

但它不起作用可能是因为“方向”是一个反应道具而不是 CSS 风格。 有没有办法在样式表文件中访问这些反应道具?

您可以使用 useMediaQuery

import useMediaQuery from '@material-ui/core/useMediaQuery';

const largeScreen = useMediaQuery(theme => theme.breakpoints.up('md'));

<Grid container direction={largescreen?"row":"column"}>

使用 flexDirection 而不是方向。

gridDirection: {
    flexDirection = "row",
    [theme.breakpoints.down('md')]: {
      flexDirection = "column",
    },
  }

最简单的方法,我相信现代的方法是使用 sx 属性。然后让 MUI 为您处理断点。 这些是撰写本文时的默认 MUI 断点。

xs = extra-small: 0px
sm = small: 600px
md = medium: 900px
lg = large: 1200px
xl = extra-large: 1536px

xs和sm一般被认为是mobile/small平板电脑。 MUI 首先是移动设备,因此在我下面的示例中,直到大小为 md 或更大时才会设置 xs 并且不会被覆盖。

<Grid container sx={{ flexDirection: { xs: "column", md: "row"} }}>

</Grid>

至少在回答日期时,Material UI 支持 directionflexDirection 带有 组件的属性,这些属性支持响应式基于传递给它的断点映射对象的值。

例如,在您的情况下,如果在大屏幕上需要 direction="row",在小屏幕上需要 direction="column",则可以将 prop 传递为: direction={{xs:'row', lg:'column'}},从而让 MUI prop 将其与 Grid 元素一起处理为:

<Grid container direction={{xs:'row', lg:'column'}}> ... </Grid>

在我看来,对于这种情况,这是在您的代码中使用它的正确样式,尽管这里的其他替代答案也很有效。

在 MUI v5 中,您可以按如下方式进行操作:

<Grid container direction={{xs: "column", md: "row"}}>

</Grid>