{showMinutes ? (
export default function Minutes() {
const { showMinutes } = useNodeListContext();
const [width, setWidth] = useState(600);
const [startX, setStartX] = useState(0);
const [startWidth, setStartWidth] = useState(0);
const handleMouseDown = (e: React.MouseEvent) => {
setStartX(e.clientX);
setStartWidth(width);
console.log(e.clientX, width, startX);
const handleMouseMove = (e: MouseEvent) => {
const newWidth = Math.max(startWidth - (e.clientX - startX), 400);
setWidth(newWidth);
};
const handleMouseUp = () => {
document.removeEventListener("mousemove", handleMouseMove);
document.removeEventListener("mouseup", handleMouseUp);
};
document.addEventListener("mousemove", handleMouseMove);
document.addEventListener("mouseup", handleMouseUp);
};
return (
<>
{showMinutes ? (
<div className="absolute right-[-32px] top-0 h-full border-2 border-blue-500" style={{ width: `${width}px` }}>
<div onMouseDown={handleMouseDown} className="right-0 top-0 h-full w-4 cursor-ew-resize" />
</div>
) : null}
</>
);
}
위와 같이 구현을 해봄
bandicam 2024-11-19 21-49-49-854.mp4
위와 같이 맨 처음 선을 드래그 할때 400으로 width가 변경되는 이상한 상황을 발견..
console.log로 e.clientX, width, startX를 찍어보니 아래와 같이 startX에 맨처음에는 0 이 들어가서 400으로 갑자기 이동하게 되는 현상이 발생 ( startX의 초기값은 0이고 상태가 비동기적으로 처리 되기 때문에 처음에는 0 이 들어가고 나중에 setStartX에 e.clientX값이 들어가게 되므로 위의 에러가 발생하게 되는 것
그래서 useRef를 사용해 비동기적으로 업데이트 되는 문제를 피하기로 함
export default function Minutes() {
const { showMinutes } = useNodeListContext();
const [width, setWidth] = useState(600);
const startXRef = useRef(0);
const startWidthRef = useRef(600);
const handleMouseDown = (e: React.MouseEvent) => {
e.preventDefault();
startXRef.current = e.clientX;
startWidthRef.current = width;
const handleMouseMove = (e: MouseEvent) => {
const newWidth = Math.max(startWidthRef.current - (e.clientX - startXRef.current), 400);
setWidth(newWidth);
};
const handleMouseUp = () => {
document.removeEventListener("mousemove", handleMouseMove);
document.removeEventListener("mouseup", handleMouseUp);
};
document.addEventListener("mousemove", handleMouseMove);
document.addEventListener("mouseup", handleMouseUp);
};
return (
<>
{showMinutes ? (
<div className="absolute right-[-32px] top-0 h-full border-2 border-blue-500" style={{ width: `${width}px` }}>
<div onMouseDown={handleMouseDown} className="right-0 top-0 h-full w-4 cursor-ew-resize" />
</div>
) : null}
</>
);
}
위와 같이 useRef를 사용함으로써 위의 에러를 해결할 수 있었다.