Material-UI 网格系统 - 每行限制 2 个项目

IT技术 reactjs material-ui
2021-05-19 08:11:59

有没有办法将网格项目限制为每行 2 个并使每行中的项目占用所有可用空间?我正在使用 ReactJS 和 MaterialUI 核心。

这是主网格:

<Grid
  container
  direction="row"
  alignContent="center"
  alignItems="center"
  wrap="wrap"
>
  <Grid item className={classes.cardDesign}>
    {showTags ? <Tags /> : null}
  </Grid>
  <Grid item className={classes.cardDesign}>
    {showReactions ? <Reactions /> : null}
  </Grid>
  <Grid item className={classes.cardDesign}>
    {showEmojiStats ? <EmojiStats /> : null}
  </Grid>
  <Grid item className={classes.cardDesign}>
    {showFilter ? <Filter /> : null}
  </Grid>
</Grid>

这些是网格项目:

<div className={classes.root}>
  <Card className={classes.cardDesign}>
    <CardContent>
      <Typography
        className={classes.title}
        color="textSecondary"
        gutterBottom
      >
        Filters
      </Typography>
      <Typography variant="h5" component="h2">
        be{bull}nev{bull}o{bull}lent
      </Typography>
      <Typography className={classes.pos} color="textSecondary">
        adjective
      </Typography>
      <Typography variant="body2" component="p">
        well meaning and kindly.
        <br />
        {'"a benevolent smile"'}
      </Typography>
    </CardContent>
    <CardActions>
      <Button size="small">Learn More</Button>
    </CardActions>
  </Card>
</div>
2个回答

Material-UI 的网格系统正是为您提供了这一点。

一般的想法是您的工作区(屏幕的宽度)被分成 12 列/容器,每个子项最多可以消耗其父容器的 %。您可以使用 12/X 类系统来决定列的宽度,因此如果您想要 2-split 可以使用6 | 6,如果您更喜欢 6-split 可以使用2 | 2 | 2 | 2 | 2 | 2,您也可以与其他人一起玩数字(例如,您可以有6 | 3 | 34 | 1 | 1 | 4 | 2。只要总和为您 12 - 您都很好。

您可以使用 5 个网格断点:xssmmdlgxl,当您需要为不同的屏幕尺寸使用不同的布局时,它们为您提供了更大的灵活性:

  • xs - 默认
  • sm - 最小宽度 600px
  • md - 最小宽度 960px
  • lg - 最小宽度 1280px
  • xl - 最小宽度 1920px

这个系统让你可以灵活地设置一个网格,在小屏幕上有 2 列,在大屏幕上有 4 列,在超大屏幕上,所有 6 个项目将在 1 行中可用:

<Grid container>
    <Grid item xs={6} lg={3} xl={2}>...</Grid>
    <Grid item xs={6} lg={3} xl={2}>...</Grid>
    <Grid item xs={6} lg={3} xl={2}>...</Grid>
    <Grid item xs={6} lg={3} xl={2}>...</Grid>
    <Grid item xs={6} lg={3} xl={2}>...</Grid>
    <Grid item xs={6} lg={3} xl={2}>...</Grid>
</Grid>

使用此系统创建其他布局也很容易,例如,如果您需要 2:10 拆分(对于左侧菜单),您可以使用:

<Grid container>
    <Grid item xs={2}>...</Grid>
    <Grid item xs={10}>...</Grid>
</Grid>

我认为您需要使用 Grid 属性 => xs、sm、md、lg 和 xl。这允许根据屏幕大小创建列大小。

我用你的例子做了一个 stackblitz:https ://stackblitz.com/edit/react-boilerplate-scalabw-cc3zyh?file = index.js