React MUI:如何使用grid组件创建一个类似于flex box的网格



我使用React和MUI作为应用程序的UI库。我有一个很大的元素列表,我想以特定的方式订购。使用Grid组件通常可以解决问题。

<Grid container
direction="row"
justifyContent="start"
alignItems="center"
spacing={4}
className={classes.Grid}
>
{Cards.map(c => (
<Grid item xs key={c._id} >
<Card id={c._id} title={c.title} description={c.description} />
</Grid>
))}
</Grid>

样式:

const useStyles = makeStyles({
Grid: {
margin: "auto!important",
width: "90vw!important",
}
});

网格中的每个元素都有特定的高度和宽度。使用代码,这就是结果

_ _ _   _ _ _   _ _ _   _ _ _   _ _ _   _ _ _   _ _ _
|     | |     | |     | |     | |     | |     | |     |
|     | |     | |     | |     | |     | |     | |     |
|_ _ _| |_ _ _| |_ _ _| |_ _ _| |_ _ _| |_ _ _| |_ _ _|
_ _ _           _ _ _          _ _ _  
|     |         |     |        |     | 
|     |         |     |        |     | 
|_ _ _|         |_ _ _|        |_ _ _| 

此外,每个项目之间的间距不会保持不变。它是由屏幕大小操纵的。屏幕越宽,每个元素之间的间隙就越大。我真正想要的

_ _ _   _ _ _   _ _ _   _ _ _   _ _ _   _ _ _   _ _ _
|     | |     | |     | |     | |     | |     | |     |
|     | |     | |     | |     | |     | |     | |     |
|_ _ _| |_ _ _| |_ _ _| |_ _ _| |_ _ _| |_ _ _| |_ _ _|
_ _ _   _ _ _   _ _ _   
|     | |     | |     | 
|     | |     | |     | 
|_ _ _| |_ _ _| |_ _ _| 

这就是我使用css flex box的地方:

<Box
sx={{
display: "flex",
justifyContent: "center" ,
gap: "20px",
flexWrap: "wrap",
margin: "auto",
width: "90vw",
}}
>
{Cards.map(c => (
<Card key={c._id} id={c._id} title={c.title} description={c.description}/>
))}
</Box>

如果屏幕尺寸太小,则该行的最后一个元素将被包裹在下一行。但只有一个问题,最后一行的列以为中心,但我只希望它们位于行的开始处,具有相同的间隙大小。那么,我如何才能真正实现与我想要的相似的目标呢

CSS

display: "grid",
gridTemplateColumns: "repeat(auto-fill, 220px)", //the width of the card 
justifyContent: "center",
gridGap: "20px",

机身

<Box className={classes.List}> //css
{Cards.map(c => (
<Grid item xs key={c._id} >
<Card id={c._id} title={c.title} description={c.description} />
</Grid>
))}
</Box>
  1. 如果您想使用网格,请在断点sxmd等中给定适当的值。此外,您不需要将道具:directionjustifyContentalignItems传递给Grid container
<Grid item xs={3} md={3} key={c._id}>
...
</Grid>

示例:

<Grid container spacing={4}>
{Cards.map((c) => (
<Grid item xs={3} md={4} key={c._id}>
...
</Grid>
))}
</Grid>

  1. 对于FlexBox:只需移除justifyContent='center'道具

相关内容

最新更新