You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

React+MaterialUI中Grid组件为何无法垂直排列元素?

为什么Material UI Grid无法让邮箱和密码输入框垂直排列?

问题原因

你的Grid组件虽然设置了direction="column",但这个布局规则只对Grid的直接子元素生效——当前Grid的直接子元素是一个<Box component="form">容器,所有输入框都嵌套在这个Box内部,Grid的垂直排列逻辑无法作用到Box里的元素。

同时,Box(form)默认是块级容器,而<TextField>和<FormControl>默认是inline-flex布局,所以它们会在同一行内并排显示,不会自动垂直排列。

修复方案

有两种简单的解决方式,根据你的需求选择:

方案1:让输入框成为Grid的直接子元素(推荐)

直接把TextField和FormControl放到Grid容器下,利用Grid的column方向实现垂直排列,同时用Grid的spacing属性统一控制间距,更符合Material UI的布局规范:

<Grid
  container
  direction="column"
  justifyContent="center"
  alignItems="center"
  spacing={2}
>
  <TextField id="standard-basic" label="Email" variant="standard" sx={{ width: "25ch" }} />
  <FormControl sx={{ width: "25ch" }} variant="standard">
    <InputLabel htmlFor="standard-adornment-password">
      Password
    </InputLabel>
    <Input
      id="standard-adornment-password"
      type={showPassword ? "text" : "password"}
      endAdornment={
        <InputAdornment position="end">
          <IconButton
            aria-label="toggle password visibility"
            onClick={handleClickShowPassword}
            onMouseDown={handleMouseDownPassword}
          >
            {showPassword ? <VisibilityOff /> : <Visibility />}
          </IconButton>
        </InputAdornment>
      }
    />
  </FormControl>
</Grid>

方案2:给Box容器添加垂直flex布局

如果需要保留form容器,直接在Box的sx属性里启用flex垂直布局,让内部元素自动垂直排列:

<Grid
  container
  direction="column"
  justifyContent="center"
  alignItems="center"
>
  <Box
    component="form"
    sx={{ 
      "& > :not(style)": { m: 1, width: "25ch" },
      display: "flex",
      flexDirection: "column",
      alignItems: "center"
    }}
    noValidate
    autoComplete="off"
  >
    <TextField id="standard-basic" label="Email" variant="standard" />
    <FormControl sx={{ m: 1, width: "25ch" }} variant="standard">
      <InputLabel htmlFor="standard-adornment-password">
        Password
      </InputLabel>
      <Input
        id="standard-adornment-password"
        type={showPassword ? "text" : "password"}
        endAdornment={
          <InputAdornment position="end">
            <IconButton
              aria-label="toggle password visibility"
              onClick={handleClickShowPassword}
              onMouseDown={handleMouseDownPassword}
            >
              {showPassword ? <VisibilityOff /> : <Visibility />}
            </IconButton>
          </InputAdornment>
        }
      />
    </FormControl>
  </Box>
</Grid>

内容的提问来源于stack exchange,提问作者Samurai

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.25 13:28:18