React/Dnd: Make a component draggable and droppable at the same time

风格不统一 提交于 2019-12-23 02:16:41

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!