长话短说,直接上使用方式!
一.使用方式:
1.安装
npm install react-dnd react-dnd-html5-backend
2.在根组件下面引入
main.tsx
import { createRoot } from 'react-dom/client';
import App from './App.tsx';
import './index.css';
import { HTML5Backend } from 'react-dnd-html5-backend';
import { DndProvider } from 'react-dnd';
createRoot(document.getElementById('root')!).render(
<DndProvider backend={HTML5Backend}>
<App />
</DndProvider>
);
3.App.tsx
import './App.css';
function Box() {
return <div className='box'></div>
}
function Container() {
return <div className="container"></div>
}
function App() {
return <div>
<Container></Container>
<Box></Box>
</div>
}
export default App;
4.App.css
.box {
width: 50px;
height: 50px;
background: blue;
margin: 10px;
}
.container {
width: 300px;
height: 300px;
border: 1px solid #000;
}
测试如下:
5.添加 useDrag--拖
import { useDrag, useDrop } from 'react-dnd';
interface ItemType {
color: string;
}
interface BoxProps {
color: string;
}
function Box(props: BoxProps) {
const ref = useRef(null);
const [, drag] = useDrag({
type: 'box',
item: {
color: props.color
}
});
drag(ref);
return <div ref={ref} className='box' style={
{ background: props.color || 'blue' }
}></div>;
}
6.添加 useDrop --放
function Container() {
const [boxes, setBoxes] = useState<ItemType[]>([]);
const ref = useRef(null);
const [, drop] = useDrop(() => {
return {
accept: 'box',
drop(item: ItemType) {
setBoxes((boxes) => [...boxes, item]);
}
};
});
drop(ref);
return <div ref={ref} className="container">
{
boxes.map(item => {
return <Box color={item.color}></Box>;
})
}
</div>;
}
7.useDrop 和 useDrag是靠什么联系的?
8.Container 接受的东西怎么渲染出来?
测试效果
9.特殊记录
本来应该是这样的:
你可以简化成这样:
他们可以相互转化