简体   繁体   English

如何使用 javascript 和 react hooks 创建可拖动组件?

[英]How to create draggable components with javascript and react hooks?

I need to add draggable divs, one for every image in an array of images, to a container.我需要将可拖动的 div(一组图像中的每个图像一个)添加到容器中。

The below works BUT only on the second drag.以下内容仅适用于第二次拖动。 ie I have to drag the component twice for it to move.即我必须拖动组件两次才能移动。 It obviously has something to do with the hooks used and how the divs are being created.它显然与使用的钩子以及如何创建 div 有关。 Any help will be appreciated.任何帮助将不胜感激。

Code sandbox代码沙箱

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

It looks like it is setting the dragId on first drag and then only on the second drag it actually drags and drops the div.看起来它在第一次拖动时设置了 dragId,然后仅在第二次拖动时才实际拖放 div。 How can I set this up so that it drags and drops on the first try?我该如何设置它以便在第一次尝试时拖放?

I should have just used React to add the functions我应该刚刚使用 React 来添加功能

const Container = ({ images, handleDrag, handleDrop }) => {
  const containerRef = useRef(null)
  
  return (
    <div ref={containerRef}>
      {images.map((image) => (
        <div
          key={image.id}
          id={image.id}
          draggable
          onDragOver={(ev) => ev.preventDefault()}
          onDrop={handleDrop}
          onDragStart={handleDrag}
          style={{
            position: 'absolute'...`,
          }}
        />
      ))}
    </div>
  )
}

export default Container

Sandbox 沙盒

visit this site I think it can be helpful:访问这个网站,我认为它会有所帮助:

https://www.w3schools.com/howto/howto_js_draggable.asp https://www.w3schools.com/howto/howto_js_draggable.asp

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM