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>

);

}

效果展示:

相关推荐
snow@li9 分钟前
Java:Java 服务器(Web 容器 / Servlet 容器)完整工作清单
java·服务器·前端
洋子1 小时前
Yank Note 系列 14 - 我和 AI 怎么一起写文章
前端·markdown
YFF菲菲兔1 小时前
React 事件系统:addTrappedEventListener
react.js
江华森1 小时前
前端构建工具 Webpack 速览
前端·webpack·node.js
谙忆10242 小时前
HTTP 图片缓存实战:Cache-Control、ETag、内容哈希文件名与 CDN 回源到底怎么配
前端
小妖6662 小时前
React input 输入卡顿问题
前端·javascript·react.js
এ慕ོ冬℘゜2 小时前
JavaScript 数据类型检测与转换、运算符超全实战详解
前端·html
kyriewen2 小时前
我用 AI 写代码快了 3 倍——然后同事的 Code Review 全变成了我的
前端·程序员·ai编程
李明卫杭州3 小时前
Vue2 portal-target 组件与 Vue3 的针对性优化
前端·javascript·vue.js
Tyler_14 小时前
iOS PlayWright mcp server
前端·ios·ai编程