安装react-draggable插件
npm install react-draggable
设置无限制的拖动范围
创建jsx文件
import React from "react";
// 引入样式
import './index.css'
// 引入拖拽插件
import Draggable from 'react-draggable';
export default function Tuo() {
return (
<div>
<div className="app">
<Draggable>
<div className="box1">我可以随意移动box1</div>
</Draggable>
<Draggable>
<div className="box2">我可以随意移动box2</div>
</Draggable>
</div>
</div>
);
}
引入css样式
.app {
background-color: red;
width: 800px;
height: 500px;
margin: auto;
position: relative;
}
.box1 {
background-color: rgb(127, 192, 127);
width: 300px;
height: 300px;
}
.box2 {
background-color: rgb(142, 200, 107);
width: 300px;
height: 300px;
}
.box3 {
background-color: rgb(112, 148, 194);
width: 300px;
height: 300px;
}
.box4 {
background-color: rgb(174, 103, 160);
width: 300px;
height: 300px;
}
设置拖拽的范围
在父级内移动
import React from "react";
// 引入样式
import "./index.css";
// 引入拖拽插件
import Draggable from "react-draggable";
export default function Tuo() {
return (
<div>
<div className="app">
{/* 限制范围*/}
<Draggable bounds={{ right: 200, left: -400, top: 0, bottom: 200 }}>
<div className="box3">我移动受限制box3</div>
</Draggable>
</div>
</div>
);
}
另一种在父级内移动
import React from "react";
// 引入样式
import "./index.css";
// 引入拖拽插件
import Draggable from "react-draggable";
export default function Tuo() {
return (
<div>
<div className="app">
{/* 限制范围另一个方式*/}
<Draggable bounds={".app"}>
<div className="box4">我移动ye受限制box4</div>
</Draggable>
</div>
</div>
);
}
效果展示: