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

React与Material UI响应式布局求助:桌面3列/移动端2列布局实现

React + Material UI 响应式布局问题解决方案

需求回顾

  • 桌面端:3等宽列布局,第一列展示行内排列的Radio按钮与标签,其余两列各放置一个Select选择器
  • 移动端:Radio组件移至顶部占满一行,下方两列各展示一个Select选择器

问题分析

原代码存在两个核心问题:

  1. 外层Grid未使用container属性,Material UI Grid布局需要container(容器)和item(子项)配合才能生效
  2. 未设置移动端(xs断点)的布局规则,导致移动端无法自动适配

修正后的代码

import { Grid, FormControlLabel, Radio, InputLabel, Select, MenuItem } from '@mui/material';

const ResponsiveLayout = () => {
  return (
    <Grid container spacing={2}>
      {/* Radio列:移动端占满一行,桌面端占1/3 */}
      <Grid item xs={12} lg={4}>
        <FormControlLabel 
          value="my quantity" 
          control={<Radio />} 
          label="My Label"
          sx={{ display: 'flex', alignItems: 'center' }} // 确保Radio和标签行内对齐
        />
      </Grid>
      {/* 第一个Select:移动端占1/2,桌面端占1/3 */}
      <Grid item xs={6} lg={4}>
        <InputLabel htmlFor="select-one">Text One</InputLabel>
        <Select 
          id="select-one"
          defaultValue={4} 
          sx={{ backgroundColor: 'lightgrey', width: '100%' }} // 设置宽度占满容器
        >
          <MenuItem value={1}>1</MenuItem>
          <MenuItem value={2}>2</MenuItem>
          <MenuItem value={3}>3</MenuItem>
          <MenuItem value={4}>4</MenuItem>
        </Select>  
      </Grid>
      {/* 第二个Select:移动端占1/2,桌面端占1/3 */}
      <Grid item xs={6} lg={4}>
        <InputLabel htmlFor="select-two">Text Two</InputLabel>
        <Select 
          id="select-two"
          sx={{ width: '100%' }}
        >
          <MenuItem value={1}>1</MenuItem>
          <MenuItem value={2}>2</MenuItem>
        </Select>
      </Grid>
    </Grid>
  );
};

export default ResponsiveLayout;

关键调整说明

  • 外层Grid添加container属性,启用Material UI的网格布局系统
  • 为每个子Grid设置xs(移动端,屏幕宽度<600px)断点规则:
    • Radio列xs={12}:移动端占满整行
    • 两个Select列xs={6}:移动端各占50%宽度
  • 为Select组件添加width: '100%',确保在不同屏幕宽度下自适应容器
  • 修复原代码的语法错误(闭合标签、缺失引号)

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.15 09:05:28