React自定义Antd抽屉Drawer组件实现鼠标拖拽控制宽度

antdesign里的Drawer组件宽度是默认的,无法通过鼠标拖拽去改变宽度。现有需求需要实现鼠标拖拽改变宽度。

实现原理很简单:

1、在Drawer里加入一个div,然后调整他的宽度成一条线的感觉,把这条线贴到Drawer的最左边,调整透明度和鼠标移入的样式,这样就伪造出了一个可拖拽的边。

2、样式实现后,这个伪造的边实现按下拖拽跟随鼠标移动,松开鼠标取消移动。

3、最后把拖拽的距离赋值给Drawer的宽度即可。

实现代码如下:

import React, { useEffect, useRef, useState } from 'react';
import { Input, Button, Drawer } from 'antd';
import style from './index.less'

const { TextArea } = Input;

const TestDrawer = props => {
    const [visible, setVisible] = useState(false);
    const showDrawer = () => {
        setVisible(true);
    };
    const onClose = () => {
        setVisible(false);
    };

    const onmousedown = function (e) {
        let isDown = false
        var x = e.clientX;
        var y = e.clientY;
        //获取左部和顶部的偏移量
        var l = e.target.offsetLeft;
        //开关打开
        isDown = true;
        // setIsDown(true)
        window.onmousemove = function (e) {
            if (isDown == false) {
                return;
            }
            //获取x和y
            var nx = e.clientX;
            //计算移动后的左偏移量和顶部的偏移量
            var nl = nx - (x - l);
            document.getElementById('line').style.left = 0 + 'px';
            document.getElementsByClassName('ant-drawer-content-wrapper')[0].style.width = document.body.clientWidth - e.screenX + 'px';
        }
        window.onmouseup = () => {
            window.onmousemove = null
        }
    };
    return (
        <>
            <Button id='aa' type="primary" onClick={showDrawer}>
                Open
            </Button>
            <Drawer id='myDrawer' title="Basic Drawer" placement="right" onClose={onClose} visible={true}>
                {/* <div className={style.bar}></div> */}
                <div id='line' onMouseDown={(e) => onmousedown(e)} className={style.line}></div>
                <p>Some contents...</p>
                <p>Some contents...</p>
                <p>Some contents...</p>
            </Drawer>
        </>
    )
}

export default TestDrawer;


.line {
    position: absolute;
    left: 0;
    height: 90vh;
    width: 5px;
    background-color: rgba(255, 0, 0, 0);
}

.line:hover {
    // background-color: rgb(99, 99, 99);
    cursor: ew-resize;
}

 

评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值