我需要将可拖动的div添加到容器中,每个div对应一个图像数组中的每个图像.
下面的方法适用于第二次拖动.i、 e.我必须拖动组件两次,使其移动.这显然与使用的钩子以及div的创建方式有关.任何帮助都将不胜感激.
const App = ({images}) => {
const [selectedImages, setSelectedImages] = useState(images)
const [dragId, setDragId] = useState()
const handleDrag = (ev) => {
setDragId(ev.currentTarget.id)
}
const handleDrop = (ev) => {
const sortedImages = sortImages(selectedImages, dragId)
setSelectedImages(sortedImages)
}
return (
<Container
images={selectedImages}
handleDrag={handleDrag}
handleDrop={handleDrop}
/>
)
}
export default App
const Container = ({ images, handleDrag, handleDrop }) => {
const ref = useRef(null)
useEffect(() => {
if (containerRef.current) {
for (let i = 0; i < images.length; ++i) {
const draggable = document.createElement('div')
draggable.ondragstart = handleDrag
draggable.ondrop = handleDrop
const style = 'position: absolute; ...'
draggable.setAttribute('style', style)
draggable.setAttribute('draggable', true)
draggable.setAttribute('id', images[i].id)
ref.current.appendChild(draggable)
}
}
}, [images, ref, handleDrag, handleDrop])
return (
<div className={'relative'}>
<div ref={ref} />
</div>
)
}
export default Container
看起来它是在第一次拖动时设置dragId,然后只有在第二次拖动时才实际拖放div.我如何设置它,使其在第一次try 时拖放?