React 九宫格拖拽排序

实现的效果:

React 九宫格拖拽排序_第1张图片
实现的效果

实现步骤

1、列表设置可拖动 draggable='true'
2、拖拽到某个元素,目标元素放大透明动画
3、记录元素移动索引,索引值不同,则排序。
4、数据排序 - splice() 方法,当前拖拽元素更换为目标元素
5、拖拽完成,当前拖拽元素样式还原

部分代码

css:

ul ,li{
  list-style: none
}
ul{
  width:480px;
}
li{
   display:inline-block;
   width:150px;
   height:150px;
   margin:5px;
   line-height:150px;
   text-align:center;
   font-size:30px;
   transition:all .5s;
   -moz-transition:all .5s;
   -webkit-transition:all .5s; 
   -o-transition:all .5s; 
}

js:

class List extends React.Component {
  constructor(props) {
    super(props);
    this.state = {...props};
  }
  
  handleData(){
    this.dragged.style.opacity = "1";
    this.dragged.style.transform = "scale(1)";
    const from = this.dragged.dataset.id;
    const to = this.target.dataset.id;
    if(from !== to ) {
      var data = this.state.data;
      data.splice(to, 0, data.splice(from, 1)[0]);
      this.setState({data: data});
      this.dragged=this.target;
    }
  }
  dragStart(e) {
    this.dragged = e.target;
  }
  drop(e) {
    e.preventDefault();
    this.dragged.style.opacity = "1";
    this.dragged.style.transform = "scale(1)";
  }
  dragOver(e) {
    e.preventDefault();
  }
  dragEnter(e) {
    e.preventDefault();
    if (e.target.tagName !== "LI") {
       return;
    }
    this.target = e.target;
    this.target.style.opacity = "0.2";
    this.target.style.transform = "scale(1.1)";
    this.handleData();
  }

  render() {
    var listItems = this.state.data.map((item, index) => {
      return (
        
  • {item.index}
  • ) }); return (
      {listItems}
    ) } } class App extends React.Component { constructor(props) { super(props); this.state = { data: [{ index: 1, bgColor: "red" },{ index: 2, bgColor: "green" },{ index: 3, bgColor: "blue" },{ index: 4, bgColor: "yellow" },{ index: 5, bgColor: "orange" },{ index: 6, bgColor: "grey" },{ index: 7, bgColor: "blueviolet" },{ index: 8, bgColor: "bisque" },{ index: 9, bgColor: "cyan" }] } } render() { return (
    ) } } ReactDOM.render( , document.getElementById('app'), );

    demo地址:https://codepen.io/itguliang-the-selector/pen/jgqVzr

    公众号文章同步:https://mp.weixin.qq.com/s/2oZuxH2BXgs8RIe22IZjPQ

    公众号:IT姑凉
    IT交流群(QQ):123493055
    博客地址: https://www.itguliang.com/
    原创文章,如需转载请注明出处,谢谢!

    React 九宫格拖拽排序_第2张图片
    微信扫一扫,可关注我的公众号

    你可能感兴趣的:(React 九宫格拖拽排序)