简体   繁体   中英

React-dnd multiple elements

I can make react-dnd drag easily having a single element to drag over however I have array of 4 fields I'd like to make draggable. In my example code down below it creates four boxes from mapping the array and each box has a className of 'element'. Which should make them all draggable however they won't move.

Here is my drag code:

 const ELEMENT = 'element';
    const [{ isDragging }, drag, dragPreview] = useDrag(() => ({
      type: ELEMENT,
      collect: (monitor) => ({
        isDragging: monitor.isDragging()
      })
    }))

Here is my draggable element:

 {FieldDetail.map((e,i) =>  
   <div key={i} ref={dragPreview} style={{ opacity: isDragging ? 0.5 : 1}}>
        <div className='element' ref={drag}></div>            
    </div>          
  )} 

Any ideas? Do I need to do something more within the type or className?

I had a similar problem - I discovered that you can call drag(ref) to take an ordinary ref and link it up with DnD.

For your use case, I would try pre-allocating the refs and calling drag on each one:

// generate refs
const refs = FieldDetal.map(x => useRef());

// call drag on each ref, linking it up with React DnD
refs.forEach(x => drag(x));

// And then when you render your component, use the refs 
{FieldDetail.map((e,i) =>  
   <div key={i} ref={dragPreview} style={{ opacity: isDragging ? 0.5 : 1}}>
        <div className='element' ref={refs[i]}></div>            
    </div>          
  )}

Not tested but this general idea should get you where you need to be. You can even make something both a drag and a drop target by calling drop(drag(ref)) .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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