react封装拖拽组件(PC)

发布于 2020-10-13  374 次阅读


简单封装一个基于react的拖拽组件

可以满足基本的需求
组件

import React from 'react';

const addEvent = (el, event, handler) => {
  if (!el) return;
  if (el.attachEvent) {
    el.attachEvent('on' + event, handler);
  } else if (el.addEventListener) {
    el.addEventListener(event, handler, false);
  } else {
    el['on' + event] = handler;
  }
};

const removeEvent = (el, event, handler) => {
  if (!el) return;
  if (el.detachEvent) {
    el.detachEvent('on' + event, handler);
  } else if (el.removeEventListener) {
    el.removeEventListener(event, handler, false);
  } else {
    el['on' + event] = null;
  }
};

// 拖拽组件
class Drag extends React.Component {
  constructor() {
    super();
    this.state = {// 用来存放当前元素的left和top值
      needX: '80vw',
      needY: '80vh',
    };
    // 用来存放鼠标按下的地方距离元素上侧和左侧边界的值
    this.disX = 0;
    this.disY = 0;
  }
  // 定义鼠标按下事件
  fnDown = (e) => {
    /*事件兼容*/
    const event = e || window.event;
    /*事件源对象兼容*/
    const target = event.target || event.srcElement;
    // 获取鼠标按下的地方距离元素左侧和上侧的距离
    this.disX = event.clientX - target.offsetLeft;
    this.disY = event.clientY - target.offsetTop;
    // 定义鼠标移动事件
    addEvent(document, 'mousemove', this.fnMove);
    // 定义鼠标抬起事件
    addEvent(document, 'mouseup', this.fnUp);
  };
  // 定义鼠标移动事件
  fnMove = (e) => {
    // 事件兼容
    const event = e || window.event;
    // 事件源对象兼容
    // const target = event.target || event.srcElement;
    this.setState({
      needX: event.clientX - this.disX,
      needY: event.clientY - this.disY,
    });
    this.props.onMove({ offsetX: this.state.needX, offsetY: this.state.needY });
  };
  fnUp = () => { // 鼠标抬起
    removeEvent(document, 'mousemove', this.fnMove);
    removeEvent(document, 'mouseup', this.fnUp);
  };
  render() {
    // 返回元素
    return (
      <div
        onMouseDown={this.fnDown}
        style={{
          ...this.props.style,
          left: this.state.needX,
          top: this.state.needY,
          cursor: 'pointer',
        }}
      >
        {this.props.children}
      </div>
    );
  }
}
export default Drag;

使用方法

使用时只需要引入组件后使用即可

        <Drag
          style={{
            width: '120px',
            height: '120px',
            backgroundColor: 'skyblue',
            position: 'absolute',
            borderRadius: '50%'
          }}
          onMove={(offet) => {
            console.log('拖拽元素当前位置:', offet);
          }}
        >
          <div style={{ textAlign: 'center' }}>内容</div>
        </Drag>

引用自 https://blog.csdn.net/weixin_37695006/article/details/83007679


I struggle for what I love, so I can be happy here.