1.首先安装 react-draggable
yarn add react-draggable / npm i react-draggable
2.在页面中导入react-draggable
import Draggable from 'react-draggable'
3.实现移动
在Draggable 中必须要用一个容器来包裹住你要拖动的东西,否则不能用
1)数据:
const arr=[
{id:1,title:123,top:700,left:1400},
{id:2,title:456,top:0,left:1400},
{id:3,title:789,top:300,left:999},
{id:4,title:100,top:650,left:1003,
]
2)前端:
// 添加数据
const add=()=>{
await axios.post("add", { title, img, top: getRandom(0, 700), left: getRandom(0,1400) })
}
// 随机位置
//最大值,最小值是通过父盒子和子盒子宽高进行计算的
const getRandom = (min, max) => {
return Math.floor(Math.random() * (max - min) + min)
}
// 设置一个拖拽元素可以移动的范围,就是拖拽元素的父节点
<div className="box">
/* <Drageable bounds={".box"}>
<div className="box1'>123</div>
</Drageable>
*/
{arr.map((ele,index)=>(
// bounds限制范围
<Draggable bounds={".box"} key={ele.id}>
<div className='box1' style={{'top':ele.top+'px','left':ele.left+'px'}} >
{ele.title}
</div>
</Draggable>
))}
<button onClick={add}>添加</button> //添加数据
</div>
3)css
.box{
width: 1500px;
height: 800px;
background: skyblue;
position: relative;
top: 100px;
}
.box1{
width: 100px;
height: 100px;
background: pink;
position: absolute;
}
效果