我正在学习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,但我不知道这是否是正确的路径。
1条答案
按热度按时间wfauudbj1#
是的,
useState
是正确的路径。考虑下面的小修改: