MUI:如何防止网格项目进入下一行?

MUI: How to prevent Grid items from going on next row?

我在 ReactJs 中使用 MUI Grid 结构来显示 5 列,如下所示:

在较小的屏幕中,列在下一行中移动。但是在较小的屏幕上,我也希望所有的列只显示在一行中,我可以通过水平滚动来访问其他列。

<Grid
  container
  spacing={2}
  style={{
    maxHeight: "100vh",
    overflowY: "auto",
    overflowX: "hidden",
    height: "440px",
    overflow: "auto",
  }}
>
  <Grid item xs={2.1}>
    {cards.map((card) => <Card props={card} /> )}
  </Grid>
</Grid>

网格基于 12 列网格布局。因此 xs 只接受以下值:

'auto' | 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12.

我建议您在开头和结尾放置一个 xs 大小等于 1 的空网格。这使 xs 的总大小等于 12。

          <Grid
            container
            spacing={2}
            style={{
              maxHeight: "100vh",
              overflowY: "auto",
              overflowX: "hidden",
              height: "440px",
              overflow: "auto",
            }}
          >
               <Grid item xs={1}/>
                 {cards.map((card) => (
                   <Grid item xs={2}>
                     <Card props={card} />
                   </Grid>
                  ))}
               <Grid item xs={1}/>
          </Grid>

因为Grid uses flexbox under the hood. You can simply set the wrap value to nowrap in your Grid container, you can see the full API of Grid component here.

<Grid
  container
  wrap="nowrap" // --> add this line to disable wrap
  sx={{ overflow: "auto" }} // --> add scrollbar when the content inside is overflowed
  spacing={8}
>
  {...}
</Grid>

现场演示