我尝试在Typescript React中通过鼠标拖动来移动div,此解决方案不起作用?

m1m5dgzv  于 2023-03-09  发布在  TypeScript
关注(0)|答案(1)|浏览(201)

这是代码。但是在第一次点击后,窗口从鼠标移开了。我怎样才能改进这段代码使它干净和工作?有没有办法使用3个使用效果?

import { BsCircle } from "react-icons/bs";
import { useState, useEffect, useRef, useCallback } from "react";

type Coordinates = {
  x: number;
  y: number;
};

const Index = () => {
  const [Mouse, setMouse] = useState<Coordinates | undefined>(undefined);
  const [newPosition, setNewPosition] = useState<Coordinates | undefined>(
    undefined
  );
  const [isMoving, setIsMoving] = useState(false);
  const [hasMoved, sethasMoved] = useState(false);
  const windowRef = useRef<HTMLDivElement>(null);
  const stylewindowContainer = hasMoved
    ? {
        top: newPosition?.y,
        left: newPosition?.x,
        position: "fixed" as "fixed",
        width: '37.5%',
        transform: 'none'
      }
    : { color: "black" };

    const startMoving = useCallback((e: MouseEvent) => {
      const Target = e.target as HTMLDivElement;
      setIsMoving(true);
      sethasMoved(true);
      setMouse({
        x: e.clientX - Target.getBoundingClientRect().left,
        y: e.clientY - Target.getBoundingClientRect().top,
      });
      if (Mouse) {
      setNewPosition({x: e.clientX - Mouse?.x, y: e.clientY - Mouse?.y})
    }}, [])

  useEffect(() => {
    if (!windowRef.current) {
      return;
    }
    
    const window: HTMLDivElement = windowRef.current;
    window.addEventListener("mousedown", startMoving);
    return () => {
      window.removeEventListener("mousedown", startMoving);
    };
  }, [startMoving]);
  
  const Moving = useCallback((e: MouseEvent) => {
    if (Mouse) {
      if (isMoving) {
        
    setNewPosition({x: e.clientX - Mouse?.x, y: e.clientY - Mouse?.y})
  }}}, [Mouse, isMoving]);
  
  useEffect(() => {
    if (!windowRef.current) {
      return;
    }
    const window: HTMLDivElement = windowRef.current;
    window.addEventListener("mousemove", Moving);
    return () => {
      window.removeEventListener("mousemove", Moving);
    };
  },[Moving]);

  const stopMoving = useCallback(() => {
    setIsMoving(false)
  },[])
  
  useEffect(() => {
    if (!windowRef.current) {
      return;
    }
    const window: HTMLDivElement = windowRef.current;
    window.addEventListener("mouseup", stopMoving);
    return () => {
      window.removeEventListener("mouseup", stopMoving);
    };
  },[stopMoving]);

  return (
    <>
      <div className="IndexFirstView">
        <div className="IndexFirstViewContainer">
          <div className="IndexHeading">
            <p>
              <span></span>
              <span>
                
              </span>
            </p>
            <p>
              <span></span>
              <span id="name">something</span>
              <span>,</span>
            </p>
            <p id="jobTitle">Hello World!</p>
            <p id="jobTitle">Hello World!</p>
            <p id="jobTitle">Hello World!</p>
            <p id="jobTitle">Hello World!</p>
            <p id="jobTitle">Hello World!</p>
          </div>
          <div className="rightSide">
            <div
              style={stylewindowContainer}
              className="windowContainer"
              ref={windowRef}
            >
              <div className="topbar">
                <div className="windowBtns">
                  <span id="windowBtn">
                    <BsCircle />
                  </span>
                  <span id="windowBtn">
                    <BsCircle />
                  </span>
                  <span id="windowBtn">
                    <BsCircle />
                  </span>
                </div>
              </div>
              <div className="windowBottomContainer">
                <p>Hello World!</p>
                <p>
                  <br />
                </p>
                <p>
                  {newPosition?.x} : {newPosition?.y}
                </p>
              </div>
            </div>
          </div>
        </div>
      </div>
      <div className="IndexSecondView">
        <p>Hello World!</p>
      </div>
    </>
  );
};

export default Index;

我最初的逻辑是获取鼠标按下在窗口中的位置,以获取我们可以按住窗口的点的相对位置。将这些坐标存储在鼠标中,然后根据mousemove事件坐标减去初始鼠标坐标来更新框的位置。这似乎不起作用。

x4shl7ld

x4shl7ld1#

我发现这个https://dev.to/roggc/how-to-continuously-drag-an-element-in-react-with-javascript-4fon,但在JS中,对于TypeScript使用这个。

import styled from 'styled-components'

export const Ball=
()=>
{
  let offsetX:number;
  let offsetY:number;

  const move=(e:MouseEvent)=>
  {
    const el=e.target as HTMLDivElement
    el.style.left = `${e.pageX-offsetX}px`
    el.style.top = `${e.pageY-offsetY}px`
  }
  const add=(e:React.MouseEvent<HTMLElement>):void =>
  {
    e.preventDefault()
    const el=e.target as HTMLDivElement
    offsetX=e.clientX - el.getBoundingClientRect().left
    offsetY=e.clientY- el.getBoundingClientRect().top

    el.addEventListener('mousemove',move)
  }

  const remove=(e:React.MouseEvent<HTMLElement>):void=>{
    const el=e.target as HTMLDivElement
    el.removeEventListener('mousemove',move)
  }
  const Wrapper=styled.div`
  width: 50px;
  height: 50px;
  border-radius: 29px;
  box-shadow: 0 0 6px;
  position: absolute;
  top: 0px;
  left: 0px;
  background-color: rgb(0,0,0,0.5);
  cursor:pointer;
  z-indez:99;
  `
  return (
    <Wrapper onMouseDown={ add }  onMouseUp={remove}/>
  )
}

相关问题