【发布时间】:2019-04-16 12:14:04
【问题描述】:
我有一个图像,当我拖动时我也想实现旋转。我想到的解决方案是使用 React DnD 来获取拖动图像位置的 xy 坐标并计算原始图像位置之间的差异。这种差异的值将构成进行旋转的基础。
我查看了 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)
【问题讨论】:
标签: javascript reactjs react-dnd