React-DnD 的使用
介绍React DnD 是一组 React 高阶组件,可以用来帮你构建复杂的拖拽接口,同时解耦你的组件。React DnD 非常适合像 Trello 和 Storify 这样的应用,在不同地方通过拖拽转移数据,而组件会改变它们的外观和应用的状态来响应拖拽事件。 基本用法
翻译成代码就是: // 1
import HTML5Backend from 'react-dnd-html5-backend';
import { DragDropContext } from 'react-dnd';
class App { ... }
export default DragDropContext(HTML5Backend)(App);
/*---------------------------*/
// 2
import { DragSource } from 'react-dnd';
class MyComponent { ... }
export default DragSource(type,spec,collect)(MyComponent);
/*---------------------------*/
// 3
import { DropTarget } from 'react-dnd';
class MyComponent2 { ... }
export default DropTarget(types,collect)(MyComponent2);
这样,MyComponent 就变得可以拖拽,而 MyComponent2 就变得可以接受拖拽了,但这并不代表 MyComponent 可以放到 MyComponent2 中! 一些概念React DnD 中有一些特殊的概念,理解这些概念之后才能活用这个库!
主要 API 介绍这些主要 API 都是通过包装你的组件,然后返回一个新的组件。 DragDropContext(backend)
export default DragDropContext(HTML5Backend)(App); DragSource(type,collect)DropTarget(type,collect)
const type = 'xxx';
const spec = { ... };
function collect(connect,monitor) { ... }
export default DragSource(type,collect)(MyComponent);
export default DropTarget(type,collect)(MyComponent2);
DragSource#spec让你的组件响应 dnd 相关事件,支持以下方法:
参数含义如下:
const spec = {
beginDrag(props) {
return {
id: props.id,content: props.content
}
}
//...
}
DropTarget#spec让你的组件响应 dnd 相关事件,支持以下方法:
参数含义如下:
const spec = {
drop(props,component) {
// 获取正在拖放的数据
const item = monitor.getItem();
// 更新组件状态
component.setState({
item
})
}
}
DragSource#collect(connect,monitor)DropTarget#collect(connect,monitor)返回一个 object,这个 object 可以会注入到组件的 props 中。
function collect(connect,monitor) {
return {
isDragging: monitor.isDragging(),connectDragSource: connect.dragSource()
}
}
class MyComponent extends Component {
render() {
// 可以访问 collect 中返回的 object
const { isDragging,connectDragSource } = this.props;
// 需要用 connect.dragSource()/connect.dropTarget() 封装自己的组件
return connectDragSource(
<div>123</div>
)
}
}
具体例子
出处
参考资料
(编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |
