如何创建100列且组件不重叠的react-grid-layout布局
如何创建100列的react-grid-layout并避免组件重叠?
问题描述
需要实现一个100列的react-grid-layout,同时保证网格项不重叠。目前减少列数能解决重叠问题,但会丢失100列的布局精度,当前组件出现重叠效果:

后续测试发现疑似CSS问题,修改官方示例后布局恢复正常:

原代码
import Button, { ButtonProps } from '@mui/material/Button'; import GridLayout from 'react-grid-layout'; const TempButton = (props: ButtonProps) => ( <Button {...props} variant="outlined" sx={{ width: '100%', height: '100%', '&:hover': { backgroundColor: 'primary.dark', opacity: [0.9, 0.8, 0.7], }, }} /> ); export const DeckLayout = (props: any) => { const layout = [ { i: '1', x: 0, y: 0, w: 2, h: 2, }, { i: '2', x: 2, y: 0, w: 1, h: 1, }, { i: '3', x: 3, y: 0, w: 2, h: 3, }, ]; return ( <GridLayout className="layout" layout={layout} cols={100} rowHeight={10} width={500}> <div key="1"> <TempButton>1</TempButton> </div> <div key="2"> <TempButton>2</TempButton> </div> <div key="3"> <TempButton>3</TempButton> </div> </GridLayout> ); };
解决方案
问题根源
100列布局下每列宽度仅为5px(500px总宽度÷100列),而MUI Button默认的内边距远大于单列宽度,加上盒模型未设置为border-box,导致Button实际宽度超出网格项分配的空间,最终引发重叠。
修复步骤
- 导入react-grid-layout基础样式:确保网格布局的核心样式生效,缺失会导致计算规则错误。
- 重置Button内边距:适配极小列宽的场景,避免内容溢出。
- 统一盒模型:给网格项容器和Button设置
box-sizing: border-box,确保内边距、边框不会占用额外宽度。
修改后的代码
import Button, { ButtonProps } from '@mui/material/Button'; import GridLayout from 'react-grid-layout'; // 引入react-grid-layout必需的样式文件 import 'react-grid-layout/css/styles.css'; import 'react-resizable/css/styles.css'; const TempButton = (props: ButtonProps) => ( <Button {...props} variant="outlined" sx={{ width: '100%', height: '100%', padding: 0, // 移除Button默认内边距,适配窄列 boxSizing: 'border-box', // 盒模型统一 '&:hover': { backgroundColor: 'primary.dark', opacity: [0.9, 0.8, 0.7], }, }} /> ); export const DeckLayout = (props: any) => { const layout = [ { i: '1', x: 0, y: 0, w: 2, h: 2, }, { i: '2', x: 2, y: 0, w: 1, h: 1, }, { i: '3', x: 3, y: 0, w: 2, h: 3, }, ]; return ( <GridLayout className="layout" layout={layout} cols={100} rowHeight={10} width={500}> {/* 网格项容器设置盒模型 */} <div key="1" style={{ boxSizing: 'border-box' }}> <TempButton>1</TempButton> </div> <div key="2" style={{ boxSizing: 'border-box' }}> <TempButton>2</TempButton> </div> <div key="3" style={{ boxSizing: 'border-box' }}> <TempButton>3</TempButton> </div> </GridLayout> ); };
额外提示
- 如果需要保留少量内边距,可将
padding设置为极小值(如padding: 1px),避免超出列宽。 - 若总宽度不变,100列的列宽极小,可能影响组件交互体验,可根据实际需求调整总
width或cols数量平衡精度与可用性。
内容的提问来源于stack exchange,提问作者joshp
相关产品推荐
相关产品推荐

