简体   繁体   中英

Is there any way to return the classname of the drop target using react-dnd?

Let's say I have this component, which represents a drop target.

import { useDrop } from 'react-dnd';
import './css/DraggableGameSlot.css';

type DraggableGameSlotProps = {
    className: string,
    text: string
}

function DraggableGameSlot(props: DraggableGameSlotProps) {        
    const [{isOver}, drop] = useDrop(() => ({
        accept: "image",
        collect: (monitor) => ({
            isOver: !!monitor.isOver(),
        })
    }))
      
    return (
        <div className={`draggable-game-slot ${props.className}`} ref={drop}>
            <span>Drop here</span>
        </div>
    )
}

export default DraggableGameSlot;

When there is an item dropped on the div, I want to get the className of the div (console.log would be fine, I will implement the logic I want myself)

How should I modify the code to get this functionality?

According to the react-dnd useDrop documentation the useDrop hook returns

Return Value Array

  • [0] - Collected Props : An object containing collected properties from the collect function. If no collectfunction is defined, an empty object is returned.
  • [1] - DropTarget Ref : A connector function for the drop target. This must be attached to the drop-target portion of the DOM.

So, having the DropTarget Ref you should be able to do something like drop.current.classList to get the classes of the drop target html element.

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