react实现拖拽排序

jsx:

import React, { useState,useCallback } from "react";
import '../css/Home.css'

let list = [];

for (let i = 0; i < 10; i++) {
  list.push(`item ${i}`);
}

const Home = () => {
  const [lists, setLists] = useState(list);
  /** 是否显示遮罩层,实现移动和鼠标松开 */
  const [dragging, setDragging] = useState(false);
  /** 设置是否可拖放 防止点击input不能长安鼠标选中 */
  const [draggable, setDraggable] = useState (true);
  /** 当前索引数 */
  const [draggingItemIndex, setDraggingItemIndex] = useState(-1);
  /** 当前点击移动列的y轴偏移量 */
  const [startPageY, setStartPageY] = useState(0);
  /** 设置移动列偏移量 */
  const [offsetY, setOffsetY] = useState(0);

  /** 鼠标点击 */
  const handleMouseDown = (event, index) => {
    setDragging(true);
    setDraggingItemIndex(index);
    setStartPageY(event.pageY);
  };

  /** 鼠标松开 */
  const handleMouseUp = (event) => {
    setDragging(false);
    setDraggingItemIndex(-1);
    setStartPageY(0);
  };

  /**
   * 当列拖放生效时,重新整理数组
   * @param arr
   * @param startIndex 当前拖放列的序号
   * @param isMoveDown 向下移动 true 向上移动false
   */
  const move = (arr, startIndex, isMoveDown) => {
    // 使用slice生成新的数组,避免对原数组产生影响
    let newArr = arr.slice();
    // 获取当前拖动的内容,需要用.[0]哈
    let moveItem = newArr.splice(startIndex, 1)[0];
    // 注意,这里的处理根据实际情况而来
    if (isMoveDown) {
      newArr.splice(startIndex + 1, 0, moveItem);
    } else {
      newArr.splice(startIndex - 1, 0, moveItem);
    }
    return newArr;
  };

  /** 鼠标移动 */
  const handleMouseMove = (event) => {
    let offset = event.pageY - startPageY;
    let draggingIndex = draggingItemIndex;
    const lineHeight = 39; // 取决列高度(比列高度少一点)
    //当移动的item没有超过list的长度, 则每往下移动超过lineHeight,就把数组中数据往后挪一位。相应的draggingItemIndex 和 startPageY都要增加一位。
    if (offset > lineHeight && draggingIndex < lists.length - 1) {
      offset -= lineHeight;
      setLists(move(lists, draggingIndex, true));
      setDraggingItemIndex(draggingIndex + 1);
      setStartPageY(startPageY + lineHeight);
      //当移动的item还是list里面, 则每往上移动超过lineHeight,就把数组中数据往前挪一位。相应的draggingItemIndex 和 startPageY都要减少一位。
    } else if (offset < -lineHeight && draggingIndex > 0) {
      offset += lineHeight;
      setLists(move(lists, draggingIndex, false));
      setDraggingItemIndex(draggingIndex - 1);
      setStartPageY(startPageY - lineHeight);
    }
    setOffsetY(offset);
  };

  /** 拖动的样式 */
  const getDraggingStyle = (index) => {
    if (index === draggingItemIndex) {
      return {
        backgroundColor: "#eee",
        transform: `translate(10px, ${offsetY}px)`,
        opacity: 0.5
      };
    } else {
      return {};
    }
  };

  /** 当鼠标移入、移出输入框时触发,防止鼠标在输入框选中文字时触发拖动 */
  const inputFocus = useCallback(
    (event, focus) => {
      event.stopPropagation();
      event.preventDefault();
      setDraggable(focus);
    },
    []
  );

  return (
    <div className="listContainer">
      {lists.map((item, index) => (
        <li
          key={item}
          draggable={draggable}
          onMouseDown={(event) => handleMouseDown(event, index)}
          style={getDraggingStyle(index)}
        >
          {item} <span>index: {index}</span>
          <input
            onMouseEnter={e => inputFocus(e, !(e.enterOrd === e.ord))}
            onMouseLeave={e => inputFocus(e, e.enterOrd === e.ord)}
          />
        </li>
      ))}
      {dragging && (
        <div
          className="coverMask"
          onMouseUp={(event) => {
            handleMouseUp(event);
          }}
          onMouseMove={(event) => {
            handleMouseMove(event);
          }}
        />
      )}
    </div>
  );
};

export default Home;

css:


.listContainer {
    position: relative;
    width: 350px;
    margin: 10px 0 0 40px;
    background-color: #eee; /*跟item移动时候的背景颜色一样,就可以产生一种移开后还留有阴影的错觉*/
  }
  
  .listContainer li {
    list-style: none;
    border-bottom: 1px solid #9c9c9c;
    padding: 10px;
    background-color: #fff;
  }
  
  .listContainer li span {
    font-size: 10px;
  }
  
  .listContainer .coverMask {
    position: fixed;
    top: 0;
    left: 0;
    width: 100%;
    height: 100%;
    background: rgba(57, 243, 0, 0);
  }
  

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值