我有一个图像,当我拖动时我也想实现旋转。我想到的解决方案是使用 React DnD 获取拖动图像位置的 xy 坐标并计算原始图像位置之间的差异。这种差异的值(value)将构成进行轮换的基础。
我查看了 ReactDnD 库中的示例,发现 DragSource 规范可以访问 Monitor 变量。此监视器变量可以访问 getInitialClientOffset()
等方法。当我实现此值的 console.log()
时,它会显示我释放鼠标时设置的最后一个坐标。
使用这个库,有没有一种简单的方法可以在我移动鼠标时获取被拖动元素的当前位置?
import React from 'react'
import { DragSource } from 'react-dnd'
// Drag sources and drop targets only interact
// if they have the same string type.
// You want to keep types in a separate file with
// the rest of your app's constants.
const Types = {
CARD: 'card',
}
/**
* Specifies the drag source contract.
* Only `beginDrag` function is required.
*/
const cardSource = {
beginDrag(props,monitor,component) {
// Return the data describing the dragged item
const clientOffset = monitor.getSourceClientOffset();
const item = { id: props.id }
console.log(clientOffset);
return item
},
isDragging(props, monitor){
console.log(monitor.getClientOffset())
},
endDrag(props, monitor, component) {
if (!monitor.didDrop()) {
return
}
// When dropped on a compatible target, do something
const item = monitor.getItem()
const dropResult = monitor.getDropResult()
console.log(item,dropResult)
//CardActions.moveCardToList(item.id, dropResult.listId)
},
}
/**
* Specifies which props to inject into your component.
*/
function collect(connect, monitor) {
return {
// Call this function inside render()
// to let React DnD handle the drag events:
connectDragSource: connect.dragSource(),
// You can ask the monitor about the current drag state:
isDragging: monitor.isDragging(),
}
}
function Card(props) {
// Your component receives its own props as usual
const { id } = props
// These two props are injected by React DnD,
// as defined by your `collect` function above:
const { isDragging, connectDragSource } = props
return connectDragSource(
<div>
I am a draggable card number {id}
{isDragging && ' (and I am being dragged now)'}
</div>,
)
}
// Export the wrapped version
export default DragSource(Types.CARD, cardSource, collect)(Card)
最佳答案
据我所知,自定义拖动层存在严重的性能问题。直接订阅底层API比较好(官方文档严重缺失,不过阅读拖拽层源码可以得到):
const dragDropManager = useDragDropManager();
const monitor = dragDropManager.getMonitor();
React.useEffect(() => monitor.subscribeToOffsetChange(() => {
const offset = monitor.getClientOffset();
// do stuff like setState, though consider directly updating style through refs for performance
}), [monitor]);
您还可以使用一些基于拖动状态的标志来仅在需要时订阅(简单的 isDragging && monitor.subscribe...
加上 dependencies 数组就可以了)。
关于javascript - React DND - 在鼠标移动时获取拖动元素的坐标,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55707908/