拖拽功能实现

该教程介绍了如何使用create-react-app初始化项目,然后通过npm安装react-draggable库,实现拖动功能。在组件中导入并配置react-draggable,设置handle属性限定拖动区域,并通过useState和useRef管理状态,限制拖动范围。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

一、准备项目
我们按常规,使用 create-react-app 这个工具来创建项目。如果你本地没有安装 npx 的话,强烈推荐,使用非常方便。

1.npx create-react-app react-draggalbe-tutorial
2.cd react-draggalbe-tutorial
3.npm start

在准备好 react 脚手架后,你就可以到目录里,执行 npm start把项目跑起来。

二、安装 react-draggable
现在执行 npm install react-draggable,执行完后应该在你的 node_modules 中就装好了 react-draggable。

三、接入 react-draggable
现在,我们希望当用户鼠标拖拽把手时,把手本身可以被移动。首先我们把 react-draggable 导入

import React, { useState, useRef } from 'react';
import './App.css';
import Draggable from 'react-draggable'; // The default


function index() {
  const [bounds, setBounds] = useState({ left: 0, top: 0, bottom: 0, right: 0 });
  const draggleRef = useRef<HTMLDivElement>(null);
  const onStart = (_event: DraggableEvent, uiData: DraggableData) => {
    const { clientWidth, clientHeight } = window.document.documentElement;
    const targetRect = draggleRef.current?.getBoundingClientRect();
    if (!targetRect) {
      return;
    }
    setBounds({
      left: -targetRect.left + uiData.x,
      right: clientWidth - (targetRect.right - uiData.x),
      top: -targetRect.top + uiData.y,
      bottom: clientHeight - (targetRect.bottom - uiData.y),
    });
  };
  return (
    <div className="App">
      {/* handle这个属性的作用就是用来选出对拖动有反应的组件部分。我们只希望在用户拖动把手时,整个组件移动。所以我们只需要用 handle 属性,选出来把手即可 */}
      {/* bounds 属性限制可以拖动的范围 */}
      <Draggable handle='.drag-handler' bounds={bounds}
        onStart={(event, uiData) => onStart(event, uiData)}>
          
          <div ref={draggleRef} className="box">
            <div className='drag-handler'>拖这里可以</div>
            <div>box 正文,拖这里拖不动</div>
          </div>
      </Draggable>

    </div>
  );
}

export default index;


四、App.css
App.css中代码

.box {
    background-color: green;
    width: 300px;
    height: 300px;
    display: flex;
    flex-direction: column;
  }
  
  .drag-handler {
    background-color: grey;
    height: 50px;
    cursor: move;
  }
  
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值