学无先后,达者为师

网站首页 编程语言 正文

react实现拖拽功能

作者:筱闯~ 更新时间: 2023-07-14 编程语言
import React, { Component } from 'react';
import './index.css'
class DragBox extends Component {
  constructor(props) {
    super(props);
    this.state = {
        left: 0,
        top: 0,
        isDragging: false,
        startX: 0,
        startY: 0
    };
  }

  handleMouseDown = (e) => {
    this.setState({
        isDragging: true,
        startX: e.clientX,
        startY: e.clientY
    });
  }

  handleMouseMove = (e) => {
    if (this.state.isDragging) {
        const offsetX = e.clientX - this.state.startX;
        const offsetY = e.clientY - this.state.startY;
        this.setState({
            left: this.state.left + offsetX,
            top: this.state.top + offsetY,
            startX: e.clientX,
            startY: e.clientY
        });
    }
  }

  handleMouseUp = (e) => {
    this.setState({
        isDragging: false
    });
  }

  render() {
    return (
        <div className="drag-box"
             style={{ left: this.state.left + 'px', top: this.state.top + 'px' ,position:'absolute'}}
             onMouseDown ={this.handleMouseDown} //鼠标按下事件
             onMouseMove={this.handleMouseMove} //鼠标移动事件
             onMouseUp={this.handleMouseUp} //鼠标抬起事件
             > 
            Drag me!
        </div>
    );
  }
}

export default DragBox;

onMouseDown //鼠标按下事件
onMouseMove //鼠标移动事件
onMouseUp //鼠标抬起事件

主要的实现思路是:鼠标移动到最后的左边距和上边距-鼠标按下的左边距和上边距然后给元素一个定位给它的left和top赋值就可实现

原文链接:https://blog.csdn.net/m0_64544033/article/details/130622286

  • 上一篇:没有了
  • 下一篇:没有了
栏目分类
最近更新