WidthProvider(Responsive) 响应式布局

  1. import { WidthProvider, Responsive } from 'react-grid-layout';
  2. import 'react-grid-layout/css/styles.css';
  3. import 'react-resizable/css/styles.css';
  4. const GridLayout = WidthProvider(Responsive);
  5. const layout = [
  6. { i: 'a', x: 0, y: 0, w: 4, h: 1, minW: 3 },
  7. { i: 'b', x: 4, y: 0, w: 4, h: 1, minW: 3, maxW: 4 },
  8. { i: 'c', x: 8, y: 0, w: 4, h: 1, minW: 3 },
  9. { i: 'd', x: 0, y: 1, w: 4, h: 1, minW: 3 },
  10. { i: 'e', x: 4, y: 1, w: 4, h: 1, minW: 3 },
  11. ];
  12. function ReactGridLayout() {
  13. return (
  14. <GridLayout
  15. className='__react-grid-layout__'
  16. // 响应式布局断点
  17. layouts={{ lg: layout, md: layout, sm: layout }}
  18. cols={{ lg: 12, md: 12, sm: 6, xs: 4, xxs: 2 }}
  19. rowHeight={80}
  20. margin={[24, 24]}
  21. containerPadding={[0, 0]}
  22. resizeHandles={['ne', 'se']}
  23. >
  24. <div key='a'>a</div>
  25. <div key='b'>b</div>
  26. <div key='c'>c</div>
  27. <div key='d'>d</div>
  28. <div key='e'>e</div>
  29. </GridLayout>
  30. )
  31. }
  32. export default ReactGridLayout;

GridLayout

默认需要设置 width,设置固定的宽度,
如果需要响应式,需要用 WidthProvider(Responsive)
image.png

  1. import GridLayout, { WidthProvider } from 'react-grid-layout';
  2. import 'react-grid-layout/css/styles.css';
  3. import 'react-resizable/css/styles.css';
  4. const layout = [
  5. { i: 'a', x: 0, y: 0, w: 4, h: 3, minW: 3 },
  6. { i: 'b', x: 4, y: 0, w: 4, h: 3, minW: 3, maxW: 4 },
  7. { i: 'c', x: 8, y: 0, w: 4, h: 3, minW: 3 },
  8. { i: 'd', x: 0, y: 1, w: 4, h: 3, minW: 3 },
  9. { i: 'e', x: 4, y: 1, w: 4, h: 3, minW: 3 },
  10. ];
  11. function ReactGridLayout() {
  12. return (
  13. <GridLayout
  14. className='__react-grid-layout__'
  15. layout={layout}
  16. cols={12}
  17. rowHeight={80}
  18. width={1200}
  19. margin={[24, 24]}
  20. containerPadding={[0, 0]}
  21. resizeHandles={['ne', 'se']}
  22. >
  23. <div key='a'>a</div>
  24. <div key='b'>b</div>
  25. <div key='c'>c</div>
  26. <div key='d'>d</div>
  27. <div key='e'>e</div>
  28. </GridLayout>
  29. )
  30. }
  31. 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的值

  1. const layout = {
  2. i: String(it.id), // 组件key值
  3. x: (index % 3) * 4, // 组件在x轴坐标
  4. y: Math.floor(index / 3), // 向下取整
  5. w: 4, // 组件宽度,占多少列
  6. h: 3, // 组件高度
  7. minW: 3, // 最小宽度
  8. minH: 2,
  9. rowHeight: 80,
  10. }

X,横向显示3栏,就 %3,显示4栏,就 %4
Y,竖向换行显示,
Ximage.png Yimage.png

react-grid-layout.less

  1. .__react-grid-layout__ {
  2. .react-grid-item {
  3. padding: 8px;
  4. background-color: rgba(218, 237, 255, 0.3);
  5. text-align: center;
  6. font-size: 24px;
  7. box-sizing: border-box;
  8. }
  9. }

拖拽的高度

每次拖拽的高度为 初始设置的 rowHeight的倍数
image.png