import React, { useRef, useCallback, useEffect, memo } from 'react'; // 独立的可拖拽面板组件 export const DraggablePanel = memo(({ initialX = 0, initialY = 0, width = 200, height = 150, bounds, children, handleContent, onPositionChange }) => { const panelRef = useRef(null); const dragRef = useRef({ isDragging: false, startX: 0, startY: 0, originX: initialX, originY: initialY }); const positionRef = useRef({ x: initialX, y: initialY }); // 初始化位置 useEffect(() => { if (panelRef.current) { panelRef.current.style.transform = `translate(${initialX}px, ${initialY}px)`; } positionRef.current = { x: initialX, y: initialY }; }, [initialX, initialY]); // 鼠标移动处理 const handleMouseMove = useCallback((e) => { const drag = dragRef.current; if (!drag.isDragging || !panelRef.current) return; let newX = drag.originX + (e.clientX - drag.startX); let newY = drag.originY + (e.clientY - drag.startY); // 边界限制 if (bounds) { newX = Math.max(0, Math.min(newX, bounds.width - width)); newY = Math.max(0, Math.min(newY, bounds.height - height)); } // 直接更新 DOM,性能最优 panelRef.current.style.transform = `translate(${newX}px, ${newY}px)`; positionRef.current = { x: newX, y: newY }; // 可选的位置变化回调 if (onPositionChange) { onPositionChange({ x: newX, y: newY }); } }, [bounds, width, height, onPositionChange]); const handleMouseUp = useCallback(() => { dragRef.current.isDragging = false; }, []); // 全局鼠标事件 useEffect(() => { window.addEventListener('mousemove', handleMouseMove); window.addEventListener('mouseup', handleMouseUp); return () => { window.removeEventListener('mousemove', handleMouseMove); window.removeEventListener('mouseup', handleMouseUp); }; }, [handleMouseMove, handleMouseUp]); // 开始拖拽 const handleMouseDown = useCallback((e) => { e.preventDefault(); e.stopPropagation(); dragRef.current = { isDragging: true, startX: e.clientX, startY: e.clientY, originX: positionRef.current.x, originY: positionRef.current.y }; }, []); return (
{/* 拖拽手柄 */} {handleContent && (
{handleContent}
)} {/* 子内容 */}
{children}
); }); export default DraggablePanel;