react antd弹窗拖动 防止超出屏幕
时间: 2023-07-23 17:21:10 浏览: 61
要实现 React Antd 弹窗的拖动并防止超出屏幕,可以使用 React DnD(React Drag and Drop)和 Antd 的 Modal 组件结合使用。具体步骤如下:
1. 安装 React DnD:`npm install react-dnd react-dnd-html5-backend`
2. 创建一个可拖拽的组件,例如 `DraggableModal` 组件,并使用 `DragSource` 高阶组件将其包装为可拖拽组件。
```jsx
import { DragSource } from 'react-dnd';
const modalSource = {
beginDrag(props) {
return {
id: props.id,
left: props.left,
top: props.top,
};
},
};
function collect(connect, monitor) {
return {
connectDragSource: connect.dragSource(),
isDragging: monitor.isDragging(),
};
}
class DraggableModal extends React.Component {
render() {
const { connectDragSource, isDragging, children } = this.props;
const opacity = isDragging ? 0.5 : 1;
return connectDragSource(
<div style={{ opacity }}>
{children}
</div>
);
}
}
export default DragSource('modal', modalSource, collect)(DraggableModal);
```
3. 在 `Modal` 组件中使用 `DraggableModal` 组件,并在 `onMouseMove` 事件中更新 `Modal` 组件的位置,同时限制其移动的范围。
```jsx
import DraggableModal from './DraggableModal';
class App extends React.Component {
constructor(props) {
super(props);
this.state = {
left: 0,
top: 0,
};
}
handleMouseMove = (e) => {
const { left, top } = this.state;
const { clientWidth, clientHeight } = document.documentElement;
const modalWidth = 520;
const modalHeight = 400;
const mouseX = e.clientX;
const mouseY = e.clientY;
let newLeft = mouseX - this.offsetX;
let newTop = mouseY - this.offsetY;
if (newLeft < 0) {
newLeft = 0;
} else if (newLeft + modalWidth > clientWidth) {
newLeft = clientWidth - modalWidth;
}
if (newTop < 0) {
newTop = 0;
} else if (newTop + modalHeight > clientHeight) {
newTop = clientHeight - modalHeight;
}
this.setState({
left: newLeft,
top: newTop,
});
}
handleMouseDown = (e) => {
this.offsetX = e.clientX - this.state.left;
this.offsetY = e.clientY - this.state.top;
document.addEventListener('mousemove', this.handleMouseMove);
}
handleMouseUp = () => {
document.removeEventListener('mousemove', this.handleMouseMove);
}
render() {
const { left, top } = this.state;
return (
<DraggableModal left={left} top={top}>
<Modal
title="Draggable Modal"
style={{ top, left }}
visible={true}
onCancel={this.handleCancel}
onMouseDown={this.handleMouseDown}
onMouseUp={this.handleMouseUp}
>
<p>Content of the modal</p>
</Modal>
</DraggableModal>
);
}
}
```
在上面的代码中,我们通过 `onMouseDown` 和 `onMouseUp` 事件监听鼠标拖动事件,并在 `onMouseMove` 事件中更新 `Modal` 组件的位置,同时限制其移动的范围不超过屏幕。