需求:需要Ant Design中的一个Modal弹框,并且可以让用户按住顶部实现拖动操作
实现:在Ant Design的Modal框的基础上,在title中添加一个onMouseDown去记录拖拽的坐标,然后将其赋值给Modal的style属性
代码部分:
import { PureComponent } from 'react';
import { Modal } from 'antd';
class ZRJModal extends PureComponent {constructor(props) {super(props)//Modal 的初始值this.state = {styleTop: 100,styleLeft: 0,}}//计算是否超出屏幕;超出后inWindow = (left:any, top:any, startPosX:any, startPosY:any) => {let H = document.body.clientHeight;let W = document.body.clientWidth;if ((left < 20 && startPosX > left) || (left > W - 20 && startPosX < left) ||(top < 20 && startPosY > top) || ((top > H - 20 && startPosY < top))) {document.body.onmousemove = null;document.body.onmouseup = null;return false;}return true;}onMouseDown = (e:any) => {e.preventDefault();let startPosX = e.clientX;let startPosY = e.clientY;const { styleLeft, styleTop } = this.state;document.body.onmousemove = e => {let left = e.clientX - startPosX + styleLeft;let top = e.clientY - startPosY + styleTop;if (this.inWindow(e.clientX, e.clientY, startPosX, startPosY)) {this.setState({styleLeft: left,styleTop: top,})}};//鼠标放开时去掉移动事件document.body.onmouseup = function () {document.body.onmousemove = null;};};render() {const { styleLeft, styleTop } = this.state;const style = { left: styleLeft, top: styleTop }return <Modaltitle={<div style={{width:'100%',cursor:'move'}} onMouseDown={this.onMouseDown}>孜然卷弹框</div>}style={style}visible={this.state.RGZJvis}onOk={this.RGZJOK}okText={'保存'}width={650}onCancel={this.RGZJhandleCancel}>孜然卷内容</Modal >}
}
export default ZRJModal