如何使用React Material UI Grid布局实现图表分组排列?
问题描述
我尝试使用@mui/material/Grid实现布局需求:在Report组件中,将Bar图表与Line图表放在同一行,Doughnut图表与PolarArea图表放在另一行。之前给图表添加了style={{display: "inline-block"}}样式,但用户体验效果很差。
核心代码
App.js
function App() { return ( <Router> <Container style={{backgroundColor: '#F3F4F6'}}> <Grid container spacing={0.5} > <Grid item xs={12}> <Routes> <Route path='/' element={<SignIn />}/> <Route path='/dashboard' element={<Dashboard/>}/> </Routes> </Grid> </Grid> </Container> </Router> ); }
Dashboard.js 组件
const Dashboard = () => { return ( <> <Grid item xs={12}> <Table/> </Grid> <Grid item xs={12}> <Report/> </Grid> </> ); }
Report.js 组件
export function Report() { return <> <Grid item xs={6}> <Bar options={barChartOptions} data={barChartData} style={{backgroundColor: 'white'}}/> </Grid> <Grid item xs={6}> <Line options={areaChartOptions} data={areaChartData} style={{backgroundColor: 'white'}}/> </Grid> <Grid item xs={6}> <Doughnut options={doughnutOptions} data={doughnutChatData} style={{backgroundColor: 'white'}}/> </Grid> <Grid item xs={6}> <PolarArea options={polarAreaOptions} data={polarAreaData} style={{backgroundColor: 'white'}}/> </Grid> <Grid item xs={12}> <Bar options={groupedBarOptions} data={groupedBarData} style={{backgroundColor: 'white'}}/> </Grid> </>; }
解决方案
问题根源在于Report组件中的Grid item没有被包裹在Grid container内——MUI Grid的布局逻辑依赖container作为父容器来管理子item的排列规则。
修改Report组件,用Grid container包裹所有图表项,利用MUI自带的响应式布局实现需求:
export function Report() { return ( <Grid container spacing={2}> <Grid item xs={6}> <Bar options={barChartOptions} data={barChartData} style={{backgroundColor: 'white'}}/> </Grid> <Grid item xs={6}> <Line options={areaChartOptions} data={areaChartData} style={{backgroundColor: 'white'}}/> </Grid> <Grid item xs={6}> <Doughnut options={doughnutOptions} data={doughnutChatData} style={{backgroundColor: 'white'}}/> </Grid> <Grid item xs={6}> <PolarArea options={polarAreaOptions} data={polarAreaData} style={{backgroundColor: 'white'}}/> </Grid> <Grid item xs={12}> <Bar options={groupedBarOptions} data={groupedBarData} style={{backgroundColor: 'white'}}/> </Grid> </Grid> ); }
说明
- 外层
Grid container负责管理内部所有item的排列,spacing属性控制图表之间的间距(可根据需求调整数值) - 所有
xs=6的item会自动在同一行排列,超出一行则自动换行,正好实现Bar+Line、Doughnut+PolarArea分两行展示的需求 - 最后一个
xs=12的图表会占满整行 - 无需额外添加
display: inline-block,MUI Grid已内置完善的布局逻辑,能保证响应式体验和规范的视觉效果
内容的提问来源于stack exchange,提问作者Dev1ce
相关产品推荐
相关产品推荐

