hooks
- 注意:hooks需要React v16.7.0-alpha以上才支持
- 只能放到function里面
使用react-dnd注意到package.json有两句
"peerDependencies": {
"react": ">= 16.8",
"react-dom": ">= 16.8"
}
官方例子
import { useState } from 'react';
function Example() {
// Declare a new state variable, which we'll call "count"
const [count, setCount] = useState(0);
return (
<div>
<p>You clicked {count} times</p>
<button onClick={() => setCount(count + 1)}>
Click me
</button>
</div>
);
}
react-dnd
import React, {useCallback, useState} from 'react'
import {DndProvider} from 'react-dnd'
import HTML5Backend from 'react-dnd-html5-backend'
import Container from './Container'
const ImageView = ({src}) => {
const [hideSourceOnDrag, setHideSourceOnDrag] = useState(true)
const toggle = useCallback(() => setHideSourceOnDrag(!hideSourceOnDrag), [
hideSourceOnDrag,
])
return (
<div className="App">
<DndProvider backend={HTML5Backend}>
<div>
<Container hideSourceOnDrag={hideSourceOnDrag} src={src} />
<p>
<label htmlFor="hideSourceOnDrag">
<input
id="hideSourceOnDrag"
type="checkbox"
checked={hideSourceOnDrag}
onChange={toggle}
/>
<small>Hide the source item while dragging</small>
</label>
</p>
</div>
{src}
</DndProvider>
</div>
)
}
export default ImageView;
import React, { useState } from 'react'
import {useDrag, useDrop} from 'react-dnd'
import update from 'immutability-helper'
const styles = {
width: '95%',
height: '90vh',
position: 'relative',
}
const style = {
position: 'absolute',
width: '100%',
backgroundColor: 'white',
cursor: 'move',
}
const Box = ({ id, left, top, hideSourceOnDrag, children }) => {
const [{ isDragging }, drag] = useDrag({
item: { id, left, top, type: 'box' },
collect: monitor => ({
isDragging: monitor.isDragging(),
}),
})
if (isDragging && hideSourceOnDrag) {
return <div ref={drag} />
}
return (
<div ref={drag} style={{ ...style, left, top }}>
{children}
</div>
)
}
const Container = ({ hideSourceOnDrag, src }) => {
const [boxes, setBoxes] = useState({
a: { top: 20, left: 80, title: 'Drag me around' },
})
const [, drop] = useDrop({
accept: 'box',
drop(item, monitor) {
const delta = monitor.getDifferenceFromInitialOffset()
const left = Math.round(item.left + delta.x)
const top = Math.round(item.top + delta.y)
moveBox(item.id, left, top)
return undefined
},
})
const moveBox = (id, left, top) => {
setBoxes(
update(boxes, {
[id]: {
$merge: { left, top },
},
}),
)
}
return (
<div ref={drop} style={styles}>
{Object.keys(boxes).map(key => {
const { left, top, title } = boxes[key]
return (
<Box
key={key}
id={key}
left={left}
top={top}
hideSourceOnDrag={hideSourceOnDrag}
>
{title}
<img src={src} alt="图片" style={{width:'150%',height:'150%',overflow:'hidden'}} />
</Box>
)
})}
</div>
)
}
export default Container