ReactJS:为什么我的可拖动弹出功能组件在拖动时不停留在鼠标下方?



大家好& &;提前感谢您的帮助!

我正在制作一个自定义的可拖动弹出功能组件,但是拖动不能按预期工作,并且div不能跟随鼠标。

我在那里有一些额外的逻辑来处理x &鼠标在div内的y偏移量,但我删除了它,以首先调试为什么拖动不能正常工作。

import React, {useState} from 'react';
import './DraggablePopup.css';
const DraggablePopup = () => {
const [isDragging, setIsDragging] = useState(false);
const [styles, setStyles] = useState({});
const handleDragStart = (e) => {                
console.log('Drag Start');
setIsDragging(true);        
}
const handleDragging = (e) => {        
if( isDragging ) {
let left = e.screenX;
let top = e.screenY;
setStyles({
left: left,
top: top
});
}
}
const handleDragEnd = () => {
console.log('Drag End');
setIsDragging(false);
}
return (
<div
className={'draggable-popup'}    // position: absolute
style={styles}
onMouseDown={handleDragStart}
onMouseMove={handleDragging}
onMouseUp={handleDragEnd}
>
<div className={'draggable-popup-header'}>
Header
</div>
<div className={'draggable-popup-body'}>
This is the draggable popup body
</div>
</div>
);
}
export default DraggablePopup;

你需要一个ref来存储之前的位置

import React, { useState, useRef } from 'react';
import './DraggablePopup.css';
const DraggablePopup = () => {
const [isDragging, setIsDragging] = useState(false);
const [styles, setStyles] = useState({});
const firstPos = useRef(null);
const dragElementRef = useRef(null);
const handleDragStart = (e) => {
firstPos.current = {
x: e.clientX,
y: e.clientY,
container: dragElementRef.current.getBoundingClientRect()
};
setIsDragging(true);
};
const handleDragging = (e) => {
if (isDragging) {
let left =
firstPos.current.container.left + e.clientX - firstPos.current.x;
let top = firstPos.current.container.top + e.clientY - firstPos.current.y;
setStyles({
left: left,
top: top
});
}
};
const handleDragEnd = (e) => {
console.log("Drag End");
setIsDragging(false);
};
return (
<div
className={"draggable-popup"} // position: absolute
style={styles}
onMouseDown={handleDragStart}
onMouseMove={handleDragging}
onMouseUp={handleDragEnd}
ref={dragElementRef}
>
<div className={"draggable-popup-header"}>Header</div>
<div className={"draggable-popup-body"}>
This is the draggable popup body
</div>
</div>
);
}

你可以检查我的代码盒。希望能有所帮助!

相关内容

  • 没有找到相关文章

最新更新