安装组件react-grid-layout
yarn add react-grid-layout
引入拖动样式,不然没有拖动效果
import '../../../node_modules/react-grid-layout/css/styles.css'
import React from 'react' import { IProps } from 'config/models' import { Row, } from 'antd' import _ from "lodash"; import GridLayout from "react-grid-layout"; import RGL, { WidthProvider } from "react-grid-layout"; import '../../../node_modules/react-grid-layout/css/styles.css' const ReactGridLayout = WidthProvider(RGL); interface LoginProp extends IProps { } interface LoginState { loginName: string, loginPassword: string, layout: any, config: { className: string, items: number, rowHeight: number, cols: number } } export default class HomePage extends React.Component<IProps, LoginState> { constructor(props: any) { super(props) const layout = this.generateLayout(); this.state = { loginName: '', loginPassword: '', layout: layout, config: { className: "layout", items: 20, rowHeight: 30, cols: 12 } } } generateDOM() { return _.map(_.range(20), function (i) { return ( <div key={i} style={{ background: '#ccc' }}> <span className="text">{i}</span> </div> ); }); } generateLayout() { /* static:true + isDraggable:true 全局拖拽,不会自动挤开其他div static:false + isDraggable:true 拖拽自动挤开其他div */ return _.map(new Array(20), function (item, i) { const y = Math.ceil(Math.random() * 4) + 1; return { x: (i * 2) % 12, y: Math.floor(i / 6) * y, w: 2, h: y, i: i.toString(), static: false, isResizable: true, isDraggable: true, isDroppable: true }; }); } // 拖动改变后的心数组 onLayoutChange(layout: any) { debugger // this.props.onLayoutChange(layout); } render() { return ( <> <ReactGridLayout layout={this.state.layout} onLayoutChange={this.onLayoutChange} {...this.state.config} > {this.generateDOM()} </ReactGridLayout> </> ) } }