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>

);

}

效果展示:

相关推荐
ashcn20014 分钟前
websocket测试通信
前端·javascript·websocket
weixin_404679316 分钟前
edge alt tab怎么关
前端·edge
CHU72903522 分钟前
线上扭蛋机拆盒小程序前端功能版块解析
前端·小程序·php
卿着飞翔37 分钟前
Vue使用yarn进行管理
前端·javascript·vue.js
夏天想43 分钟前
vue通过iframe引入一个外链地址,怎么保证每次切换回这个已经打开的tab页的时候iframe不会重新加载
前端·javascript·vue.js
GISer_Jing44 分钟前
2026年前端开发目标(From豆包)
前端·学习·aigc
军军君011 小时前
Three.js基础功能学习十一:动画与音频
前端·javascript·3d·js·threejs·三维
我即将远走丶或许也能高飞1 小时前
reduxjs/toolkit 的学习使用
前端·javascript·学习·reactjs
Coder_Boy_1 小时前
基于SpringAI的在线考试系统-知识点管理模块完整优化方案
java·前端·人工智能·spring boot
摘星编程1 小时前
OpenHarmony环境下React Native:Sensors摇一摇换图
javascript·react native·react.js