react-draggable实现拖拽

安装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>

);

}

效果展示:

相关推荐
鱼与宇9 分钟前
前端Web(html+css+js+vue3)
前端
雪芽蓝域zzs2 小时前
(六)打包优化 + Nginx 部署完整配置 + 项目收尾
前端·vue.js
研☆香2 小时前
聊一聊前端的常见字 关键字
开发语言·前端·javascript
东风破_2 小时前
JWT 1:从一个登录请求开始,理解 React 项目里的 API 层与 Mock
前端·后端
东风破_2 小时前
JWT 3:为什么 Token 要放进 Authorization?Axios 拦截器到底解决了什么?
前端·后端
东风破_2 小时前
JWT 5:路由守卫是什么?把整个 JWT 登录鉴权流程串起来
前端·后端
东风破_2 小时前
JWT 2:HTTP 是无状态的,为什么登录成功后还要给 Token?
前端·后端
东风破_3 小时前
JWT 4:Zustand 到底解决了什么?为什么登录状态要放进 Store?
前端·后端
IT_陈寒3 小时前
Vite动态导入差点让我秃头,原来问题出在这
前端·人工智能·后端
白泽_hunter3 小时前
项目里最常见的 5 个 this 指向坑:从规则到实战彻底讲透
前端