resizeHandles文档
x: 组件在x轴坐标
y: 组件在y轴坐标
w: 组件宽度
h: 组件高度
i: 组件key值
addItem
const addItem = {
x: (widgets.length * 4) % 12, // x
y: Infinity, // puts it at the bottom
w: 4, // w 占据多少列
h: 2, // height = 2 * rowHeight 100 = 200
i: String(Date.now()), // 必须是 String
resizeHandles: ['s', 'w', 'e', 'n', 'sw', 'nw', 'se', 'ne'], // ['se']
// isResizable: false, // 禁止缩放
// isDraggable: false, // 禁止拖拽
// isDroppable: true, // default, false
// isBounded: true,
};
拖拽方向
// 's' - South handle (bottom-center)
// 'w' - West handle (left-center)
// 'e' - East handle (right-center)
// 'n' - North handle (top-center)
// 'sw' - Southwest handle (bottom-left)
// 'nw' - Northwest handle (top-left)
// 'se' - Southeast handle (bottom-right)
// 'ne' - Northeast handle (top-right)
resizeHandles: ?Array<'s' | 'w' | 'e' | 'n' | 'sw' | 'nw' | 'se' | 'ne'> = ['se']
WithResponsive
import React, { useState } from 'react';
import { Layout, Button } from 'antd';
import { WidthProvider, Responsive } from 'react-grid-layout';
import './react-grid-layout.less';
const ResponsiveReactGridLayout = WidthProvider(Responsive);
const INIT_STATE = {
className: 'layout',
// 响应式布局划分成几列
cols: { lg: 12, md: 12, sm: 6, xs: 4, xxs: 1 },
// 响应式布局中组件的行高
rowHeight: 100, // 默认 150px
layouts: {},
margin: [24, 24], // 卡片之间的x, y间距,默认 10px
// isResizable: false,
// 布局响应式断点
// breakpoints: { lg: 1200, md: 996, sm: 768, xs: 480, xxs: 0 },
};
const style = {
position: 'relative',
width: '100%',
height: '100%',
backgroundColor: '#f90',
marginBottom: 32,
};
function DragLayout() {
const [state, setState] = useState(INIT_STATE);
const [widgets, setWidgets] = useState([]);
// 生成布局中的组件
function generateDOM() {
return widgets.map((item, i) => {
return (
// data-grid为每一个组件绑定了布局属性
<div key={i} data-grid={item}>
<section style={style}>
<h2>{i}</h2>
<span
style={{ position: 'absolute', right: 8, top: 8, padding: 8 }}
onClick={() => onRemove(i)}
>X</span>
</section>
</div>
);
});
}
// 新增组件
function onAdd() {
const ITEM = {
// 一行显示多少个卡片,组件在 x轴的坐标
x: (widgets.length * 4) % 12,
// 组件在 Y轴的坐标
y: Infinity, // puts it at the bottom
// 组件的宽度 & 高度
w: 4, // w 占据多少列
h: 2, // height = 2 * rowHeight 100 = 200
// 组件的 key值,必须是 String
i: String(Date.now()),
resizeHandles: ['s', 'e', 'se'], // ['se']
// isResizable: false, // 禁止缩放
// isDraggable: false, // 禁止拖拽
// isDroppable: true, // default, false
isBounded: true,
};
const newData = widgets.concat({ ...ITEM });
setWidgets(newData);
}
function onRemove(index) {
const filterData = widgets.filter((_, i) => index != i);
setWidgets(filterData);
}
// 组件发生拖拽,或放大缩小时触发
function onLayoutChange(layout, layouts) {
setState(prevState => ({
...prevState,
layouts,
}));
}
return (
<Layout>
<Layout.Header>
<Button onClick={onAdd}>添加图表</Button>
</Layout.Header>
<div style={{ background: 'rgba(63,81,181,.3)', minHeight: 900 }}>
<ResponsiveReactGridLayout
{...state}
onLayoutChange={onLayoutChange}
>
{generateDOM()}
</ResponsiveReactGridLayout>
</div>
</Layout>
);
}
export default DragLayout;