drag-modal-antd
v1.1.3
Published
a solution for antd draggable modal
Downloads
33
Readme
一个基于React、Antd实现的可拖拽模态框解决方案
安装
npm install drag-modal-antd
使用示例
import React from 'react';
import ReactDOM from 'react-dom';
import DragModal from 'drag-modal-antd';
import { Button } from 'antd';
const App = () => {
return (
<DragModal title={2333} visible={true} > <Button>点击</Button>
</DragModal>
)
}
ReactDOM.render(
<App />,
document.getElementById('root')
);
源码如下(Source code)
import React, { useEffect } from 'react';
import { Modal } from 'antd';
const DragModal = (props) => {
let count = 0;
const {
children,
wrapClassName,
title,
width = 520,
...otherProps
} = props;
let state = {
id: Number(Math.random()* 10 + Date.now()),
dragWrapDom: null,
dragDom: null,
draging: false,
tLeft: 0,
tTop: 0,
point: [0, 0],
rect: [0, 0, 0, 0]
};
const getDragDom =()=> {
let timer = setTimeout(() => {
const dragWrapDom = document.getElementsByClassName(`d_${state.id}`)[0];
if (dragWrapDom) {
state.dragWrapDom = dragWrapDom;
let dragDom = dragWrapDom.getElementsByClassName('ant-modal')[0]
if (dragDom) {
state.dragDom = dragDom
let modalWidth = state.dragDom.offsetWidth;
let modalHeight = state.dragDom.offsetHeight;
let screenWidth = window.innerWidth
let screenHeight = window.innerHeight
state.points = [(screenWidth - modalWidth) / 2, (screenHeight - modalHeight) / 2]
state.rect = [screenWidth, screenHeight, modalWidth, modalHeight]
}
}
});
return () => clearTimeout(timer)
};
useEffect(getDragDom)
const onMouseUp =(e)=> {
e.preventDefault();
state.dragging = false;
document.onmousemove = null;
};
const onMouseDown =(e)=> {
e.preventDefault();
state.dragging = true;
const dragDomRect = state.dragDom.getBoundingClientRect();
state.tLeft = e.clientX - dragDomRect.left + state.points[0];
state.tTop = e.clientY - dragDomRect.top + state.points[1];
onMouseMove(state.dragDom);
};
const onMouseMove =(node)=> {
count ++;
if(count % 2 === 0) {
return;
}
document.onmousemove = e => {
e.preventDefault();
if (state.dragging) {
let left = e.clientX - state.tLeft
let top = e.clientY - state.tTop
if (state.points[0] + left > 0 && state.points[0] + left + state.rect[2] < state.rect[0]) {
if (state.points[1] + top > 0 && state.points[1] + top + state.rect[3] < state.rect[1]) {
node.style.left = left + 'px';
node.style.top = top + 'px';
}
}
}
};
};
const onContentMoseDown =(e)=> {
state.dragging = false;
document.onmousemove = null;
}
return (
<Modal
width={width}
wrapClassName={`drag_modal d_${state.id} ${wrapClassName}`}
title={
<div
className="drag_title"
onMouseDown={onMouseDown}
onMouseUp={onMouseUp}
>
{title}
</div>
}
{...otherProps}
centered={true}
>
<div onMouseDown={onContentMoseDown}>
{children}
</div>
</Modal>
)
}
export default DragModal;