在material-ui中更改Grid Item堆叠的顺序

2022-01-18 00:00:00 reactjs grid layout css material-ui

每当浏览器缩小时,我对网格项的堆叠顺序有疑问.

I have a problem with the order of stacking of grid items whenever browser shrinks.

这是我在普通桌面屏幕上想要的(lg):

This is what I want on the normal desktop screen(lg):

---------------------------------------------
|   col 1     |         col 2       | col 3 |
---------------------------------------------

但缩小浏览器后,我得到以下结果:

But After Shrinking the browser I am getting the following result:

-------------------------
|     col 1             |
-------------------------
-------------------------
|     col 2             |
-------------------------
-------------------------
|     col 3             |
-------------------------

我可以用 Material ui Grid layout 在手机屏幕上实现这个吗:

Can I with material ui Grid layout achieve this on a mobile screen:

-------------------------
|     col 1             |
-------------------------
-------------------------
|     col 3             |
-------------------------
-------------------------
|     col 2             |
-------------------------

我已阅读有关更改同一主题的 CSS 网格顺序的文章,但如何使用 material-ui 网格布局来实现这一点.

I have read articles on changing the order of CSS-grids for the same topic but how to achieve this using material-ui Grid layout.

推荐答案

扩展到 Olivier 的回答 Material-UI 在其实现中大量使用 CSS flexbox 布局.正如文档引用的那样

Extending to Olivier's answer Material-UI heavily uses the CSS flexbox layout within its implementation. As the documentation quotes

flex 容器是由元素生成的盒子,其计算显示为 flex 或 inline-flex.flex 容器的流入子项称为 flex 项,并使用 flex 布局模型进行布局.

A flex container is the box generated by an element with a computed display of flex or inline-flex. In-flow children of a flex container are called flex items and are laid out using the flex layout model.

所以 Grid 项目是 flex 项目,而 Grid Container 是外行语言中的 flexbox 容器.因此,当 Box 或 Grid Container 调整大小时,我们可以使用 Grid 项目的 order 属性来更改它们的相对外观顺序.因此,通过以下方式将样式传递给网格项应该可以解决

So Grid items are flex items and Grid Container is flexbox container in laymans language. Hence we can use the order property on Grid items to change their relative order of appearance when the Box or Grid Container resizes. So passing the style in the following manner to the grid item should work out

  itemStyle: {
    order: ${Desired_order_before_Shrinking},

    [theme.breakpoints.up(`${DesiredScreenSize}`)]: {
      order: ${Desired_order_after_Shrinking},
    },
 
  }

最后执行 <Grid item xs={12} md={6} className={this.props.classes.itemStyle}> 将重新排序该项目.希望它能创造更好的理解.

Finally doing <Grid item xs={12} md={6} className={this.props.classes.itemStyle}> will reorder that item. Hope it creates better understanding.

更新:材质 UI V5.感谢@Adam Cooper 在下面的回答

UPDATE: Material UI V5. Thanks to @Adam Cooper's answer below

<Grid container spacing={2}>
  <Grid item md={12} lg={4} order={{ md: 1, lg: 1 }}>col 1</Grid>
  <Grid item md={12} lg={4} order={{ md: 3, lg: 2 }}>col 2</Grid>
  <Grid item md={12} lg={4} order={{ md: 2, lg: 3 }}>col 3</Grid>
</Grid>

相关文章