WidthProvider(Responsive) 响应式布局
import { WidthProvider, Responsive } from 'react-grid-layout';
import 'react-grid-layout/css/styles.css';
import 'react-resizable/css/styles.css';
const GridLayout = WidthProvider(Responsive);
const layout = [
{ i: 'a', x: 0, y: 0, w: 4, h: 1, minW: 3 },
{ i: 'b', x: 4, y: 0, w: 4, h: 1, minW: 3, maxW: 4 },
{ i: 'c', x: 8, y: 0, w: 4, h: 1, minW: 3 },
{ i: 'd', x: 0, y: 1, w: 4, h: 1, minW: 3 },
{ i: 'e', x: 4, y: 1, w: 4, h: 1, minW: 3 },
];
function ReactGridLayout() {
return (
<GridLayout
className='__react-grid-layout__'
// 响应式布局断点
layouts={{ lg: layout, md: layout, sm: layout }}
cols={{ lg: 12, md: 12, sm: 6, xs: 4, xxs: 2 }}
rowHeight={80}
margin={[24, 24]}
containerPadding={[0, 0]}
resizeHandles={['ne', 'se']}
>
<div key='a'>a</div>
<div key='b'>b</div>
<div key='c'>c</div>
<div key='d'>d</div>
<div key='e'>e</div>
</GridLayout>
)
}
export default ReactGridLayout;
GridLayout
默认需要设置 width,设置固定的宽度,
如果需要响应式,需要用 WidthProvider(Responsive)
import GridLayout, { WidthProvider } from 'react-grid-layout';
import 'react-grid-layout/css/styles.css';
import 'react-resizable/css/styles.css';
const layout = [
{ i: 'a', x: 0, y: 0, w: 4, h: 3, minW: 3 },
{ i: 'b', x: 4, y: 0, w: 4, h: 3, minW: 3, maxW: 4 },
{ i: 'c', x: 8, y: 0, w: 4, h: 3, minW: 3 },
{ i: 'd', x: 0, y: 1, w: 4, h: 3, minW: 3 },
{ i: 'e', x: 4, y: 1, w: 4, h: 3, minW: 3 },
];
function ReactGridLayout() {
return (
<GridLayout
className='__react-grid-layout__'
layout={layout}
cols={12}
rowHeight={80}
width={1200}
margin={[24, 24]}
containerPadding={[0, 0]}
resizeHandles={['ne', 'se']}
>
<div key='a'>a</div>
<div key='b'>b</div>
<div key='c'>c</div>
<div key='d'>d</div>
<div key='e'>e</div>
</GridLayout>
)
}
export default ReactGridLayout;
- rowHeight,组件的行高
- onLayoutChange:响应式布局中的组件发生拖拽或者放大缩小时触发该函数
layout 参数
- i,组件的 key,必须是 string
- x,组件在 X轴的坐标
- y,组件在 Y轴的坐标
- w,width,组件宽度,占多少列
- h,height,组件高度,= 几倍的 rowHeight,2就是 2 * rowHeight
- minW,最小宽度
- minH,最小高度
显示 3栏的 layout布局,需要动态计算 x,y的值
const layout = {
i: String(it.id), // 组件key值
x: (index % 3) * 4, // 组件在x轴坐标
y: Math.floor(index / 3), // 向下取整
w: 4, // 组件宽度,占多少列
h: 3, // 组件高度
minW: 3, // 最小宽度
minH: 2,
rowHeight: 80,
}
X,横向显示3栏,就 %3,显示4栏,就 %4
Y,竖向换行显示,
X Y
react-grid-layout.less
.__react-grid-layout__ {
.react-grid-item {
padding: 8px;
background-color: rgba(218, 237, 255, 0.3);
text-align: center;
font-size: 24px;
box-sizing: border-box;
}
}
拖拽的高度
每次拖拽的高度为 初始设置的 rowHeight的倍数