如何在嵌套网格中对齐项目(React Material UI)

How to align items across nested Grid (React Material UI)

我现在正在使用 React material UI 网格组件来构建我的网页,但我遇到了有关跨嵌套网格对齐项目的问题。现在的视图是这样的:

但我希望右半边的项目被拉伸以与底部的左半边对齐,理想情况下应该是这样的:

代码是这样的:

import React from 'react';
import { makeStyles } from '@material-ui/core/styles';
import Paper from '@material-ui/core/Paper';
import Grid from '@material-ui/core/Grid';

const useStyles = makeStyles((theme) => ({

  paper: {
    padding: theme.spacing(1),
    textAlign: 'center',
    color: theme.palette.text.secondary,
  },
}));

export default function NestedGrid() {
  const classes = useStyles();

  function FormRow3() {
    return (
      <React.Fragment>
        <Grid item xs={4}>
          <Paper className={classes.paper}>item</Paper>
        </Grid>
        <Grid item xs={4}>
          <Paper className={classes.paper}>item</Paper>
        </Grid>
        <Grid item xs={4}>
          <Paper className={classes.paper}>item</Paper>
        </Grid>
      </React.Fragment>
    );
  }
  function FormRow2() {
    return (
      <React.Fragment>
        <Grid item xs={12}>
          <Paper className={classes.paper}>item</Paper>
        </Grid>
      </React.Fragment>
    );
  }

  return (
    <div >
      <Grid container spacing={1}>
        <Grid container item xs={6} spacing={3}>
          <FormRow3 />
          <FormRow3 />
        </Grid>
        <Grid container item xs={6} spacing={3}>
          <FormRow2 />
        </Grid>
      </Grid>
    </div>
  );
}

我这里还有一个沙箱:https://codesandbox.io/s/material-demo-forked-xunx7

有人能帮忙吗?

编辑: 使用@nipuna777 answer(flex=1),我可以对齐网格中的项目。但我发现如果更复杂的场景,像这样:

顶部、底部和右侧部分可能没有完全对齐。那么如何让所有这些边界完美对齐呢??

上面的代码在这里: https://codesandbox.io/s/material-demo-forked-imrrh?file=/demo.js

一种可能的解决方案需要进行以下更改:

  1. container={true} 添加到 Grid 元素,以便它为子组件创建一个 flex 容器。 (在这种情况下,子组件将是 Paper.
<Grid item xs={12} container={true}>
  <Paper className={classes.paper}>item</Paper>
</Grid>
  1. classes.paper定义中,添加flex: 1,确保Paper元素在容器中占满space。
paper: {
  flex: 1,
  padding: theme.spacing(1),
  textAlign: "center",
  color: theme.palette.text.secondary
}

您可以在此处查看工作示例:https://codesandbox.io/s/material-demo-forked-ud6um?file=/demo.js

如果您查看检查器,您会发现问题是您设置了内边距而不是高度设置。

<div class="MuiPaper-root makeStyles-paper-1 MuiPaper-elevation1 MuiPaper-rounded">
 item
</div>

您应该将 padding: 8px; 替换为 height: 100%;

所以您可以在上面的元素中使用 类 来应用您的新样式。

你试过把中间的间距Grid缩小到2,

return (
    <div>
      <Grid container spacing={1}>
        <Grid container item xs={6} spacing={3}>
          <FormRow1 />
          <FormRow3 />
        </Grid>
        <Grid container item xs={6} spacing={2}>
          <FormRow2 />
        </Grid>
        <Grid item xs={12} spacing={3}>
          <FormRow4 />
        </Grid>
      </Grid>
    </div>
  );

无法在评论中 post 这么多代码,因此 post 作为答案。