使用react-dnd拖拽库时如何获取放置目标(drop target)的className?
解决方案
你只需要在useDrop的配置项中添加drop回调函数即可,该回调会在元素被成功放置到当前目标上时触发。你可以通过两种方式获取div的className:
方式1:直接拼接已知类名(推荐,性能更好)
因为组件渲染的div类名是固定前缀draggable-game-slot加传入的props.className,可以直接拼接后打印:
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", // 新增drop回调,放置完成时自动触发 drop: () => { const fullClassName = `draggable-game-slot ${props.className}`; console.log('放置目标的className:', fullClassName); // 你的后续逻辑可以在此处实现 }, collect: (monitor) => ({ isOver: !!monitor.isOver(), }) })) return ( <div className={`draggable-game-slot ${props.className}`} ref={drop}> <span>Drop here</span> </div> ) } export default DraggableGameSlot;
方式2:通过DOM节点获取(适合类名会动态变化的场景)
如果你的div类名存在其他动态修改逻辑,可以额外绑定一个ref获取真实DOM的className:
import { useDrop } from 'react-dnd'; import { useRef } from 'react'; import './css/DraggableGameSlot.css'; type DraggableGameSlotProps = { className: string, text: string } function DraggableGameSlot(props: DraggableGameSlotProps) { // 新增DOM ref用于获取实际渲染的节点属性 const slotRef = useRef<HTMLDivElement>(null); const [{isOver}, drop] = useDrop(() => ({ accept: "image", drop: () => { if(slotRef.current) { console.log('放置目标的className:', slotRef.current.className); } // 你的后续逻辑可以在此处实现 }, collect: (monitor) => ({ isOver: !!monitor.isOver(), }) })) return ( // 同时绑定react-dnd的drop ref和自定义的DOM ref <div ref={node => { drop(node); slotRef.current = node; }} className={`draggable-game-slot ${props.className}`}> <span>Drop here</span> </div> ) } export default DraggableGameSlot;
内容的提问来源于stack exchange,提问作者Octavian Niculescu
相关产品推荐
相关产品推荐

