gpt4 book ai didi

javascript - react /Dnd : Make a component draggable and droppable at the same time

转载 作者:行者123 更新时间:2023-11-30 07:53:46 25 4
gpt4 key购买 nike

有多个元素,我希望它们同时可拖放 - 使用 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)

最佳答案

这可以通过 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;

同样的例子可用 here .不过它使用生成器。

关于javascript - react /Dnd : Make a component draggable and droppable at the same time,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46257882/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com