JS 拖放:将一个元素放在另一个元素之上会用第一个元素替换 dataTransfer 数据

JS Drag and Drop: Dropping one element on top of another replaces dataTransfer data with first elements

我正在用 React 编写一个简单的国际象棋游戏,并尝试使用拖放 API 来简化棋子的拖放。一切都按预期工作,除了当一块捕获另一块时。例如,如果白车捕获黑兵,则白车移动到黑兵先前的位置,而黑兵离开棋盘。但是下一次我尝试移动白车时,它移动了被捕获的黑兵。

无论使用哪两块,此行为都是 100% 一致的。 piece 1捕获piece 2,现在piece 1的dataTransfer数据就是piece2的。

我已经缩小了范围,我认为问题出在 dataTransfer 对象上。

棋子的 dragStart 代码

_onDragStart( e ){
    e.dataTransfer.items.clear();
    e.dataTransfer.clearData( "text/plain" );
    e.dataTransfer.effectAllowed = "move";
    e.dataTransfer.dropEffect = "move";
    e.dataTransfer.setData( "text/plain", JSON.stringify( this.metaData ) );
}

图块的放置处理程序代码

_onDrop( e ){
    this.onDrop({
        index: this.state.index,
        piece: JSON.parse( e.dataTransfer.getData( "text/plain" ) )
    });
}

1) Try replace the old piece using dropBefore.replaceWith(yourNewChessPiece);

2) are you Missing the target element Id , not setting it, not sure if your metaData variable has it

一些samples

// cache you element/variables to simplify the later
// I think you are missing this, I cant tell what your this.metaData holds
chessPieceToAddToTile = document.getElementById(data),
dropBefore = ev.target;

// using childNode.replaceWith() to insert the 
// so, *** REPLACE old piece with your new chessPieceToAddToTile Node
// dropBefore Node:
dropBefore.replaceWith(chessPieceToAddToTile);

childNode.replaceWith().... Ref And Node.replaceChild().

Troubleshooting: Simplify it a bit so you can see what's happening, something like this in your drag handler, drop handlers

console.log("dragStart: dropEffect = " + ev.dataTransfer.dropEffect + " ; effectAllowed = " + ev.dataTransfer.effectAllowed ; chessPieceToAddToTile... blah blah);