[英]Delete draggable object in react-dnd
I'm using react-dnd.我正在使用反应-dnd。 I want to delete a draggable object once it's been used.
我想在使用后删除可拖动的 object。 I took the react-dnd multiple type example and added a delete on drop.
我采用了 react-dnd 多类型示例并添加了删除时删除。
Current behavior: 1. Drag Banana, the top right dustbins is highlighted 2. Drag Bottle into either of the dustbins on the left 3. Drag Banana again, now the left two dustbins are highlighted当前行为: 1. 拖动 Banana,右上方的垃圾箱高亮显示 2. 将 Bottle 拖入左侧的任一垃圾箱 3. 再次拖动 Banana,现在左侧的两个垃圾箱高亮显示
Expected behavior: 1. Drag Bottle into either of the dustbins on the left 2. Drag Banana, the top right should be highlighted预期行为: 1. 将瓶子拖入左侧的任一垃圾箱 2. 拖动香蕉,右上角应突出显示
What is going on here, and how do I fix it?这是怎么回事,我该如何解决?
https://codesandbox.io/s/pensive-wildflower-q2oxo?file=/src/Dustbin.jsx https://codesandbox.io/s/pensive-wildflower-q2oxo?file=/src/Dustbin.jsx
You are using array index as key to the boxes and doing removals.您正在使用数组索引作为框的键并进行删除。 Don't use indexes as key specially when dealing with item-removal operations.
在处理项目删除操作时,不要专门使用索引作为键。 Instead, maintain a unique id for Boxes.
相反,为 Boxes 维护一个唯一的 id。 Also update the state of the boxes properly.
还要正确更新盒子的 state。
Code Snippet代码片段
const Container = () => {
const [dustbins, setDustbins] = useState([
{ accepts: [ItemTypes.GLASS], lastDroppedItem: null },
{ accepts: [ItemTypes.FOOD], lastDroppedItem: null },
{
accepts: [ItemTypes.PAPER, ItemTypes.GLASS, NativeTypes.URL],
lastDroppedItem: null
},
{ accepts: [ItemTypes.PAPER, NativeTypes.FILE], lastDroppedItem: null }
]);
const [boxes, setBoxes] = useState([
{ id: 1, name: "Bottle", type: ItemTypes.GLASS },
{ id: 2, name: "Banana", type: ItemTypes.FOOD },
{ id: 3, name: "Magazine", type: ItemTypes.PAPER }
]);
const [droppedBoxNames, setDroppedBoxNames] = useState([]);
function isDropped(boxName) {
return droppedBoxNames.indexOf(boxName) > -1;
}
const handleDrop = useCallback(
(index, item, id) => {
const { name } = item;
setDroppedBoxNames(prev => [...prev, name]);
// setDroppedBoxNames(
// update(droppedBoxNames, name ? { $push: [name] } : { $push: [] })
// );
setBoxes(prev => prev.filter(x => x.id !== id));
// setBoxes(update(boxes, { $splice: [[item.id, 1]] }));
setDustbins(
update(dustbins, {
[index]: {
lastDroppedItem: {
$set: item
}
}
})
);
},
[droppedBoxNames, boxes, dustbins]
);
return (
<div>
<div style={{ overflow: "hidden", clear: "both" }}>
{dustbins.map(({ accepts, lastDroppedItem }, index) => (
<Dustbin
accept={accepts}
lastDroppedItem={lastDroppedItem}
onDrop={item => handleDrop(index, item)}
key={index}
/>
))}
</div>
<div style={{ overflow: "hidden", clear: "both" }}>
{boxes.map(({ name, type, id }, index) => (
<Box
key={id}
id={id}
name={name}
type={type}
isDropped={isDropped(name)}
/>
))}
</div>
</div>
);
};
export default Container;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.