一、实现流程
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);