手写一个React拖拽调整大小的组件

一、实现流程

1.使用React.cloneElement加强包裹组件,在包裹的组件设置绝对定位,并在组件内加上四个可调整大小的拖动条,在点击拖动条并进行拖动时会改变DragBox的大小,如下:
在这里插入图片描述
2.使用:

<DragBox dragAble={
   true} minWidth={
   350} minHeight={
   184} edgeDistance={
   [10, 10, 10, 10]} dragCallback={
   this.dragCallback} >
	{
   /* 使用DragBox拖动组件包裹需要调整大小的盒子 */}
   <div style={
   {
    top: 100 + 'px', left: 100 + 'px', width: 350, height: 184, backgroundColor: "white" }}>
        <div style={
   {
    backgroundColor: "yellow", width: "100%", height: 30 }}></div>
        <div style={
   {
    backgroundColor: "green", width: "100%", height: 30 }}></div>
        <div style={
   {
    backgroundColor: "blue", width: "100%", height: 30 }}></div>
    </div>
</DragBox>

二、代码

DragBox组件

import React, {
    Component, Fragment } from 'react';
import styles from "./DragBox.less";

/**
 * 拖拽的公共组件
 * 接收参数:
 *      dragAble:是否开启拖拽
 *      minWidth:最小调整宽度
 *      minHeight:最小调整高度
 *      edgeDistance:数组,拖拽盒子里浏览器上下左右边缘的距离,如果小于这个距离就不会再进行调整宽高
 *      dragCallback:拖拽回调
 * 
 * 使用:
 *      在DragBox组件放需要实现拖拽的div,DragBox组件内会设置position:absolute(React.cloneElement)
 */
class DragBox extends Component {
   
    constructor(props) {
   
        super(props);
        // 父组件盒子
        this.containerRef = React.createRef();
        // 是否开启尺寸修改
        this.reSizeAble = false;
        // 鼠标按下时的坐标,并在修改尺寸时保存上一个鼠标的位置
        this.clientX, this.clientY;
        // 鼠标按下时的位置,使用n、s、w、e表示
        this.direction = "";
        // 拖拽盒子里浏览器上下左右边缘的距离,如果小于这个距离就不会再进行调整宽高
        this.edgeTopDistance = props.edgeDistance[0] || 10;
        this.edgeBottomDistance = props.edgeDistance[1] || 10;
        this.edgeLeftDistance = props.edgeDistance[2] || 10;
        this.edgeRightDistance = props.edgeDistance[3] || 10;
    }

    componentDidMount(){
   
        // body监听移动事件
        document.body.addEventListener('mousemove', this.move);
  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值