import React, { Component } from 'react'
import { DndProvider, DragSource, DropTarget } from 'react-dnd'
import HTML5Backend from 'react-dnd-html5-backend'
// 被拖拽的项
const source = {
// 卡片开始被拖拽时触发
beginDrag(props) {
// console.log('开始被拖拽', props.index)
return {
index: props.index
}
},
// 卡片结束拖拽时触发
endDrag(props) {
// console.log('结束拖拽', props.index)
}
}
// 拖拽目的项
const target = {
props(props, monitor) {
const dragIndex = monitor.getItem().index // 被拖拽前的位置
const hoverIndex = props.index // 拖拽后的位置
// 拖拽位置不变
if (dragIndex === hoverIndex) {
return;
}
props.handleMove(dragIndex, hoverIndex)
}
}
const DraggbleDiv = props => {
const { connectDragSource, connectDropTarget, item, index } = props
return (
connectDragSource(connectDropTarget(
<div key={index}>{item.title}</div>
))
)
}
const DraggbleBox = (
DragSource('test', source, (connect, monitor) => ({
connectDragSource: connect.dragSource()
})))(DropTarget('test', target, (connect, monitor) => ({
connectDropTarget: connect.dropTarget()
}))(DraggbleDiv)
)
class demo extends Component {
constructor(){
super()
this.state = {
list: [{
title: '更新内容'
},{
title: '更新时间'
},{
title: '学习提醒'
}]
}
this.handleMove = this.handleMove.bind(this)
}
handleMove(dragIndex, hoverIndex){
const { list } = this.state
const temp = list[dragIndex]
if(dragIndex > hoverIndex){
for(let i = dragIndex; i > hoverIndex; i--){
list[i] = list[i-1]
}
}else{
for(let i = dragIndex; i < hoverIndex; i++){
list[i] = list[i+1]
}
}
list[hoverIndex] = temp
this.setState({ list })
}
render() {
const { list } = this.state
return (
<div>
<DndProvider backend={HTML5Backend}>
{
list.map((item, index) => (
<DraggbleBox
item={item}
index={index}
key={index}
handleMove={this.handleMove}
/>
))
}
</DndProvider>
</div>
)
}
}
export default demo
react-dnd 最简单易懂的列表排序
最新推荐文章于 2024-06-22 10:10:44 发布