您可能偶然发现了堆叠ES7装饰器的示例中的部分:
@DropTarget(ItemTypes.CARD, cardTarget, connect => ({
connectDropTarget: connect.dropTarget()
}))
@DragSource(ItemTypes.CARD, cardSource, (connect, monitor) => ({
connectDragSource: connect.dragSource(),
isDragging: monitor.isDragging()
}))
这里给出了在ES5或ES6中实现等效代码的解决方案 - http://gaearon.github.io/react-dnd/docs-faq.html - 使用lodash流函数来组合函数 - 但是在示例代码中有一点错误,它缺少数组括号。因此,正确的代码应该是:
export default flow([
DragSource(/* ... */),
DropTarget(/* ... */)]
)(YourComponent);
附:即使第1阶段激活,Babel REPL似乎也不支持装饰器,我收到以下错误:
repl: Decorators are not supported yet in 6.x pending proposal update.
3 | connectDropTarget: connect.dropTarget()
4 | }))
> 5 | export default class Card extends Component {
| ^
6 | render() {
7 | return <div>asdas</div>
8 | }
_.flow
是一个很好的解决方案,但没有必要安装下划线并为这一项任务添加导入。
DragSource()
返回一个函数,该函数将React组件类作为输入,并返回一个新的React组件类,它将充当拖动源。 DropTarget()
做同样的事情。知道这一点,我们可以简单地写:
DragSource(_itemType_, _sourceSpecification_, _sourceCollector_)(
DropTarget(_itemType_, _targetSpecification, _targetCollector_)(YourComponent))
DropTarget(/*...*/)(YourComponent)
将返回目标组件类,并且 DragSource(/*...*/)
可以读入新创建的组件类并吐出最终的组件类,它既是放置目标,也是拖动源。
有点冗长,但它可以在不使用外部库的情况下完成工作,如果这是您正在寻找的。
如果你不了解任何es6 \ 7功能,你总是可以去babeljs.io并尝试一下。关于装饰器 - 函数装饰器接受一个函数,包装(或修饰)它的调用并返回包装器,这会改变默认行为。您可以在此处查看示例并阅读相关内容: http://javascript.info/tutorial/decorators
这里 是你在babeljs的榜样
看起来像 HongJheLi 在ES6中重新制作了一个回购示例: https://github.com/HongJheLi
问题的关键:
export default flow([
DragSource(ItemTypes.CARD, cardSource, (connect, monitor) => ({
connectDragSource: connect.dragSource(),
isDragging: monitor.isDragging(),
})),
DropTarget(ItemTypes.CARD, cardTarget, connect => ({
connectDropTarget: connect.dropTarget(),
}))
])(Card);