3

有多个元素,我想同时获得可拖动和可放置的元素 - 使用react dnd. 这意味着我需要将其中一个元素拖放到另一个元素上。

首先,我为 MyComponent 定义了 dragSource。到目前为止有效。但是我该如何为同一个组件设置 DropTarget 呢?

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)
4

1 回答 1

8

这可以通过 React-DND 实现。它需要将可拖动元素同时导出为源和目标。

您可以将组件定义为

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;

此处提供了相同的示例。虽然它使用生成器。

于 2018-01-11T07:50:45.797 回答