Reactdnd实现拖拽最简单代码直接可以跑

57次阅读

共计 1549 个字符,预计需要花费 4 分钟才能阅读完成。

不多说,直接上代码

react-dnd 需要 react 版本 > 16.6 , 貌似与 react.memo 方法有关

import React from 'react'
// DragDropContext 类似 React 的 Context
// DragSource 高阶组件 包裹被拖的元素
// DropTarget 高阶组件 包裹被释放的元素 
import {DragDropContext, DragSource, DropTarget} from 'react-dnd';
// HTML5Backend  这个库是必须的,类似于 React 的合成事件
// 解决浏览器差异,抽象事件操作为可以处理的 state
import HTML5Backend from 'react-dnd-html5-backend';
import "./index.css"

const data = [{id: 10, text: '1'},
  {id: 11, text: '2'},
  {id: 12, text: '3'},
  {id: 13, text: '4'},
  {id: 14, text: '5'}
]

const datas = {data}

class Item extends React.Component {constructor(props) {super(props)
  }

  render() {const {connectDragSource, connectDropTarget, move, ...restProps} = this.props;
    return (
      connectDragSource(
        connectDropTarget(<div {...restProps}>{restProps.text}</div>
        )
      )
    )
  }
}


const dragNode = DragSource('li', {beginDrag(props, monitor, component) {
    return {index: props.index,};
  },
}, connect => ({connectDragSource: connect.dragSource(),
}))(Item);


const DropNode = DropTarget('li', {drop(props, monitor) {const dragIndex = monitor.getItem().index;
      const hoverIndex = props.index;
      if (dragIndex === hoverIndex) return;
      props.move(dragIndex, hoverIndex);
      //monitor.getItem().index = hoverIndex;}
  }, function (connect) {
    return {connectDropTarget: connect.dropTarget()
    }
  }
)(dragNode)


class Demo extends React.Component {
  state = datas;

  moveRow = (start, end) => {let {data} = this.state;
    let temp = data[start]
    data[start] = data[end];
    data[end] = temp;
    this.setState({data})
  }

  render() {

    return (
      <div className='move'>
        {this.state.data.map( (item, index) => {

            const prop = {
              move: this.moveRow,
              key: item.id,
              id: item.id,
              text: item.text,
              index: index
            }
            return <DropNode {...prop}/>

          })
        }
      </div>
    )
  }
}

export default DragDropContext(HTML5Backend)(Demo);

正文完
 0