React/Dnd:同时使组件可拖放 [英] React/Dnd: Make a component draggable and droppable at the same time
本文介绍了React/Dnd:同时使组件可拖放的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
有多个元素,我想同时使用react dnd
使其可拖放.
这意味着我需要将其中一个元素拖放到另一个元素上.
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.
首先,我为MyComponent定义了dragSource.到目前为止有效. 但是我该如何为同一组件设置DropTarget?
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)
推荐答案
React-DND可以做到这一点. 它需要将可拖动元素同时导出为源"和目标".
This is possible with React-DND. It requires exporting the draggable element both as Source and Target.
您可以将组件定义为
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.
这篇关于React/Dnd:同时使组件可拖放的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文