最新在使用 react-dnd ,如下例子,useDrag 会返回一个 drag ,这个需要挂载到一个组件的 ref 上去 如果是一个 html element 或者 class component ,是有 ref 的,但是一个函数组件,是没有 ref 的,怎么挂上去呢?
export const Box = function Box({ name }) { const [{ isDragging }, drag] = useDrag(() => ({ type: ItemTypes.BOX, item: { name }, end: (item, monitor) => { const dropResult = monitor.getDropResult(); if (item && dropResult) { window.alert(`You dropped ${item.name} into ${dropResult.name}!`); } }, collect: mOnitor=> ({ isDragging: monitor.isDragging(), handlerId: monitor.getHandlerId() }) })); const opacity = isDragging ? 0.4 : 1; return ( <div ref={drag} style={{ ...styleBox, opacity }} data-testid={`box-${name}`} > {name} </div> ); }; 如果是个函数组件,比如,div 换成一个 function component ,drag 无法生效。 debug into react-dnd 的源代码,就会发现,找不到 drag source,因为 ref 一直是 null
export const Box = function Box({ name }) { const [{ isDragging }, drag] = useDrag(() => ({ type: ItemTypes.BOX, item: { name }, end: (item, monitor) => { const dropResult = monitor.getDropResult(); if (item && dropResult) { window.alert(`You dropped ${item.name} into ${dropResult.name}!`); } }, collect: mOnitor=> ({ isDragging: monitor.isDragging(), handlerId: monitor.getHandlerId() }) })); const opacity = isDragging ? 0.4 : 1; rturn ( <FunctionComponent ref={drag} style={{ ...styleBox, opacity }} data-testid={`box-${name}`} > {name} </FunctionComponent> ); }; 当然,这个 FunctionComponent 也是一个复杂组件,可能级联下去,孙子的孙子也是一个 div 元素。 但是怎么能够把 react-dnd 的的这个 drag ,传递给孙子的孙子的 div 元素 ref 元素呢?
谢谢!
