如何在React中使用Material UI实现两个表格并排显示?
Material UI 双表格并排实现方案
现有基础代码
已封装好的基础表格组件如下:
function BasicTable() { return ( <TableContainer component={Paper}> <Table sx={{ minWidth: 300 }} aria-label="simple table"> <TableHead> <TableRow> <TableCell>Dessert (100g serving)</TableCell> <TableCell align="right">Calories</TableCell> <TableCell align="right">Fat (g)</TableCell> <TableCell align="right">Carbs (g)</TableCell> <TableCell align="right">Protein (g)</TableCell> </TableRow> </TableHead> <TableBody> {rows.map((row) => ( <TableRow key={row.name} sx={{ '&:last-child td, &:last-child th': { border: 0} }} > <TableCell component="th" scope="row"> {row.name} </TableCell> <TableCell align="right">{row.calories}</TableCell> <TableCell align="right">{row.fat}</TableCell> <TableCell align="right">{row.carbs}</TableCell> <TableCell align="right">{row.protein}</TableCell> </TableRow> ))} </TableBody> </Table> </TableContainer> ); }
原有写法问题
之前尝试的代码混用了浮动、清除浮动、多种display属性,属性冲突导致无法并排:
- 两个容器都设置了
clear: both,会强制元素独占一行换行展示 - 同时使用float布局和inline-flex/inline-block布局,样式互相覆盖
- 宽度属性
width:'200'为无效值,sx中字符串类型宽度需要带单位,数字类型会默认按px计算
原有错误代码参考:
<Box sx={{ float:'left', clear: 'both', p:10, m:5, bgcolor: 'background.paper', borderRadius: 1, display: 'inline-flex', direction:'row' }} > <BasicTable/> </Box> <Box sx={{ float: 'right', clear: 'both', width:'200', p:10, m:5, bgcolor: 'background.paper', borderRadius: 1, display: 'inline-block', direction:'row' }} > <BasicTable/> </Box>
正确实现代码
直接使用MUI原生支持的Flex布局即可,所有样式都写在sx属性中,不需要引入独立CSS文件:
{/* 外层容器控制横向排列 */} <Box sx={{ display: 'flex', flexDirection: 'row', gap: 24, // 控制两个表格之间的间距,单位px padding: 16, }} > {/* 两个表格容器各占1份宽度,实现等宽并排 */} <Box sx={{ flex: 1 }}> <BasicTable /> </Box> <Box sx={{ flex: 1 }}> <BasicTable /> </Box> </Box>
适配优化
- 移动端适配:给外层Box添加
flexWrap: 'wrap',给内层表格容器添加minWidth: 300,屏幕宽度不足时表格会自动换行堆叠 - 自定义宽度:如果不需要等宽,可直接给内层Box设置固定宽度,例如第一个表格设置
sx={{ width: 400 }},第二个设置sx={{ flex: 1 }}即可实现固定宽度+自适应宽度的并排效果 - 样式调整:内外层Box都可以通过sx添加背景色、圆角、边距等属性,和普通MUI组件写法一致
内容的提问来源于stack exchange,提问作者user460567
相关产品推荐
相关产品推荐

