????????本篇文章将会使用react实现简单拖放功能。
import React, {useState} from "react";
import { Button } from "antd";
import "./LayoutResize.css";
export const LayoutResize = () => {
const [state,setState] = useState({
dragging: false,
startPageX: 0,
siderWidth: 150,
})
// 鼠标点击事件
const handleMouseDown = evt => {
setState({
...state,
dragging: true,
startPageX: evt.pageX,
});
};
// 鼠标抬起事件
const handleMouseUp = () => {
setState({
...state,
dragging: false,
});
};
// 鼠标移动事件
const handleMouseMove = evt => {
if (!state.dragging){ // 没有拖拽直接返回
return;
}
console.log('move')
let siderWidth = state.siderWidth + evt.pageX - state.startPageX;
if (siderWidth < 20 || siderWidth > 300) {
return;
}
setState({
...state,
siderWidth,
startPageX: evt.pageX,
});
};
const pxWidth = `${state.siderWidth}px`;
return (
<div className="app-layout-resize" style={{ paddingLeft: pxWidth }}>
<div className="header">Header</div>
<div className="sider" style={{ width: pxWidth }}>
Sider
</div>
<div className="content" style={{ left: pxWidth }}>
Content
</div>
<div className="footer" style={{ left: pxWidth }}>
Footer
</div>
<div
className="sider-resizer"
style={{ left: pxWidth }}
onMouseDown={handleMouseDown}
onMouseMove={handleMouseMove}
onMouseUp={handleMouseUp}
/>
</div>
);
}
????????LayOutResize组件是一个实现侧边栏拖放功能得布局组件。组件由左侧的sider,右侧的header,content,header,以及透明的sider-resizer。
????????sider-resizer做到可以滑动,基于onMouseDown,onMouseMove,onMouseup方法实现,动态修改左侧sider的大小来实现。
.app-layout-resize {
width: 500px;
height: 400px;
position: relative;
background-color: #eee;
text-align: center;
padding-left: 150px;
line-height: 60px;
}
.app-layout-resize .header {
border-bottom: 2px solid #fff;
}
.app-layout-resize .content {
position: absolute;
bottom: 60px;
top: 60px;
left: 0;
right: 0;
}
.app-layout-resize .sider {
width: 150px;
position: absolute;
border-right: 2px solid #fff;
top: 0;
left: 0;
bottom: 0;
}
.app-layout-resize .footer {
border-top: 2px solid #fff;
bottom: 0;
left: 150px;
right: 0;
position: absolute;
}
.app-layout-resize .sider-resizer {
position: absolute;
left: 148px;
width: 6px;
top: 0;
bottom: 0;
cursor: col-resize;
}