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;
}