问题
There are multiple elements, which I want to get draggable and droppable at the same time - using react dnd
.
That means I need to drag one of the elements and drop it over another element.
First I defined the dragSource for MyComponent. That works so far. But how do I have to setup the DropTarget for the same component?
import React, { Component } from 'react'
import { DragSource, DropTarget } from 'react-dnd'
const elementSource = {
beginDrag (props) {
return { }
}
}
const elementTarget = {
drop (props, monitor) { }
}
function collect (connect, monitor) {
return {
connectDragSource: connect.dragSource(),
isDragging: monitor.isDragging(),
connectDropTarget: connect.dropTarget(),
isOver: monitor.isOver()
}
}
class MyComponent extends Component {
render () {
const { connectDragSource, isDragging, connectDropTarget, isOver } = this.props
return connectDragSource(
<div style={{ opacity: isDragging ? 0.5 : 1 }} >
Just an example
</div>
)
}
}
export default DragSource('element', elementSource, collect)(MyComponent)
回答1:
This is possible with React-DND. It requires exporting the draggable element both as Source and Target.
You could define the component as
class MyComponent extends Component {
render () {
const { connectDragSource, isDragging, connectDropTarget, isOver } = this.props
return connectDragSource(connectDropTarget(
<div style={{ opacity: isDragging ? 0.5 : 1 }} >
Just an example
</div>
))
}
}
MyComponent = DragSource('MyComponent', elementSource, (connect,
monitor) => ({
connectDragSource: connect.dragSource(),
isDragging: monitor.isDragging()
}))(MyComponent);
MyComponent = DropTarget('MyComponent', elementTarget, connect => ({
connectDropTarget: connect.dropTarget(),
}))(MyComponent);
export default MyComponent;
An example for the same is available here. It uses generators though.
来源:https://stackoverflow.com/questions/46257882/react-dnd-make-a-component-draggable-and-droppable-at-the-same-time