javascript 变量设置为www.example.com后为空e.target,请React

jk9hmnmh  于 2023-02-15  发布在  Java
关注(0)|答案(1)|浏览(136)

我正在学习React,我创造了一个国际象棋游戏。
我必须模拟一个拖拽和点击系统来使棋子移动。
函数setActivePiece在鼠标按下时调用,它将变量activePiece设置为被点击的棋子(仅当它是棋子而不是被点击的棋盘时),movePiece仅在鼠标松开时调用(点击结束或拖动结束)。
拖动系统工作,但我希望能够点击一块,然后点击的位置,我想要的棋子移动。
点击后,activePiece被设置为点击的片段(使用www.example.com),并调用函数movePiece(导致点击调用setActivePiece和movePiece),但在第二次点击期间,变量activePiece的值为空,实际上片段不会移动。e.target) and the function movePiece is called (cause a click call both setActivePiece and movePiece), but during the second click the value of the Variable activePiece is null, in fact the piece wont move.
有什么建议吗?
这是密码。

function Board(){
    const [pieces, setPieces] = useState([]);
    const boardRef = useRef();
    let activePiece = null;

    function movePiece(e) {
            if (activePiece === null)
            return;

        //determinate the position in the board (from cordinate to index of the board)
        setPieces(prevState => {
            const updatePieces = prevState.map(p => {
                //finding the right piece
                if (p.id === activePiece.id){
                    let lenghtmovingPiece = boardRef.current.offsetWidth / 8;
                    //aggiorno la posizione (int(posmovingPiece - posBoard / lenghtmovingPiece))
                    p.x = parseInt((e.clientX - boardRef.current.getBoundingClientRect().x) / lenghtmovingPiece);
                    p.y = parseInt((e.clientY - boardRef.current.getBoundingClientRect().y) / lenghtmovingPiece);
                }
                return p;
            })
            //reset hte active piece
            activePiece = null
            return updatePieces;
        })
    }

    function setActivePiece(e) {
        //no preview image
        e.preventDefault();
        //click of the board
        if (e.target.id === "boardImg")
            return;
        activePiece = e.target
    }

    function dragPiece(e){
        //nothing selected
        if (activePiece === null)
            return;

        //set the element new position when dragged
        //newPos = mousePos - spazio tra la finestra e la scacchiera (perche' i piece sono absolute alla scacchiera) - meta' della grandezza del piece (= larghezzaBoard / 4)
        activePiece.style.left = e.clientX - boardRef.current.getBoundingClientRect().x - boardRef.current.getBoundingClientRect().x/4 + "px";
        activePiece.style.top = e.clientY - boardRef.current.getBoundingClientRect().y - boardRef.current.getBoundingClientRect().x/4 + "px";
    }

    useEffect(() => {
        // createMatch("matches", "match0/logs/log1", {})
        // createMatch("matches", "match0", objBoard)
        setPieces(generateBoard())
    }, [activePiece]);

    return(
        <div id="board" onMouseDown={setActivePiece} onMouseUp={movePiece} onMouseMove={dragPiece} >
            <img ref={boardRef} id="boardImg" src={boardImg} alt="board" draggable="false"/>
            {
                //pieces of the board
                pieces.map(piece => return <Piece key={uuidv4()} piece={piece}/>)
            }
        </div>
    )

}

还尝试使用useState,但我不知道这是否是正确的路径。

wfauudbj

wfauudbj1#

是的,useState是正确的路径。考虑下面的小修改:

export default function Board() {
  const [activePiece, setActivePiece] = useState(null);
  const [pieces, setPieces] = useState([]);
  const boardRef = useRef();

  function movePiece(e) {
    if (activePiece === null) return;

    //determinate the position in the board (from cordinate to index of the board)
    setPieces((prevState) => {
      const updatePieces = prevState.map((p) => {
        //finding the right piece
        if (p.id === activePiece.id) {
          let lenghtmovingPiece = boardRef.current.offsetWidth / 8;
          //aggiorno la posizione (int(posmovingPiece - posBoard / lenghtmovingPiece))
          p.x = parseInt(
            (e.clientX - boardRef.current.getBoundingClientRect().x) /
              lenghtmovingPiece
          );
          p.y = parseInt(
            (e.clientY - boardRef.current.getBoundingClientRect().y) /
              lenghtmovingPiece
          );
        }
        return p;
      });
      //reset the active piece
      setActivePiece(null);
      return updatePieces;
    });
  }

  function onMouseDown(e) {
    //no preview image
    e.preventDefault();
    //click of the board
    if (e.target.id === "boardImg") return;
    setActivePiece(e.target);
  }

  function dragPiece(e) {
    //nothing selected
    if (activePiece === null) return;

    const updatedActivePiece = { ...activePiece };

    //set the element new position when dragged
    //newPos = mousePos - spazio tra la finestra e la scacchiera (perche' i piece sono absolute alla scacchiera) - meta' della grandezza del piece (= larghezzaBoard / 4)
    updatedActivePiece.style.left =
      e.clientX -
      boardRef.current.getBoundingClientRect().x -
      boardRef.current.getBoundingClientRect().x / 4 +
      "px";
    updatedActivePiece.style.top =
      e.clientY -
      boardRef.current.getBoundingClientRect().y -
      boardRef.current.getBoundingClientRect().x / 4 +
      "px";

    setActivePiece(updatedActivePiece);
  }

  useEffect(() => {
    // createMatch("matches", "match0/logs/log1", {})
    // createMatch("matches", "match0", objBoard)
    setPieces(generateBoard());
  }, [activePiece]);

  return (
    <div
      id="board"
      onMouseDown={onMouseDown}
      onMouseUp={movePiece}
      onMouseMove={dragPiece}
    >
      <img
        ref={boardRef}
        id="boardImg"
        src={boardImg}
        alt="board"
        draggable="false"
      />
      {
        //pieces of the board
        pieces.map((piece) => (
          <Piece key={uuidv4()} piece={piece} />
        ))
      }
    </div>
  );
}

相关问题