react-dnd 移出删除
时间: 2023-08-09 16:09:58 浏览: 143
对于React DnD,要实现移出删除(drag and drop with remove),可以按照以下步骤进行:
1. 创建一个可拖拽的组件,如下所示:
```
import React from 'react';
import { useDrag } from 'react-dnd';
const ItemTypes = {
CARD: 'card'
};
const Card = ({ id, text }) => {
const [{ isDragging }, drag] = useDrag({
item: { id, type: ItemTypes.CARD },
collect: monitor => ({
isDragging: monitor.isDragging()
})
});
return (
<div ref={drag} style={{ opacity: isDragging ? 0.5 : 1 }}>
{text}
</div>
);
};
export default Card;
```
2. 创建一个可放置的组件,如下所示:
```
import React from 'react';
import { useDrop } from 'react-dnd';
const ItemTypes = {
CARD: 'card'
};
const DropZone = ({ onDrop }) => {
const [{ isOver }, drop] = useDrop({
accept: ItemTypes.CARD,
drop: (item, monitor) => {
onDrop(item);
},
collect: monitor => ({
isOver: monitor.isOver()
})
});
return (
<div ref={drop} style={{ background: isOver ? 'lightgray' : 'white' }}>
Drop Here
</div>
);
};
export default DropZone;
```
3. 在父组件中,使用这两个组件,并实现移出删除功能,如下所示:
```
import React, { useState } from 'react';
import Card from './Card';
import DropZone from './DropZone';
const App = () => {
const [cards, setCards] = useState([
{ id: 1, text: 'Card 1' },
{ id: 2, text: 'Card 2' },
{ id: 3, text: 'Card 3' }
]);
const handleDrop = droppedCard => {
setCards(prevCards => prevCards.filter(card => card.id !== droppedCard.id));
};
return (
<div>
{cards.map(card => (
<Card key={card.id} id={card.id} text={card.text} />
))}
<DropZone onDrop={handleDrop} />
</div>
);
};
export default App;
```
这样,当你将一个卡片拖放到“Drop Here”区域时,该卡片将从列表中移除。
阅读全文