自定义Taro拖拽列表排序组件

本文介绍了如何使用Taro.js和React开发一个可以进行拖拽排序的组件,展示了如何处理列表项的拖动、放置和排序状态的更新,以及onChange事件的处理。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

效果如下

在这里插入图片描述

代码如下

import React, { useState } from 'react'
import styles from './index.module.less'
import { View } from '@tarojs/components'
import Taro from '@tarojs/taro'
import { useThrottleFn } from 'ahooks'

interface IProps {
  list: any[]
  itemHeight: number
  renderItem: any
  onchange: (value: any) => void
}

const DragSortList: React.FC<IProps> = (props) => {
  const [list, setList] = useState(
    props.list.map((item, index) => ({
      ...item,
      top: index * props.itemHeight
    }))
  )
  const [dragging, setDragging] = useState(null)
  const [startY, setStartY] = useState(0)

  //  拖拽长按
  const handleLongPress = (e, index) => {
    // 震动
    Taro.vibrateShort()
    setStartY(e.touches[0].clientY)
    setDragging(index)
  }

  const { run: handleTouchMove } = useThrottleFn(
    (e) => {
      if (dragging === null) return
      const newY = e.touches[0].clientY
      const diff = newY - startY
      // 计算新的 top 值
      let newTop = list[dragging].top + diff
      // 确保元素不会超出列表范围
      newTop = Math.max(0, newTop)
      newTop = Math.min(newTop, (list.length - 1) * props.itemHeight)
      // 计算拖拽元素的当前索引
      const currentIndex = Math.round(newTop / props.itemHeight)
      // 只有当拖拽元素移动到新位置时才更新列表
      if (currentIndex !== dragging) {
        const newList = [...list]
        // 移除拖拽元素并插入到新位置
        const [draggingItem] = newList.splice(dragging, 1)
        newList.splice(currentIndex, 0, draggingItem)
        // 更新列表中每个元素的 top 值
        newList.forEach((item, index) => {
          item.top = index * props.itemHeight
        })
        setList(newList)
        // @ts-ignore
        setDragging(currentIndex) // 更新拖拽元素的索引
      }
      // 更新 startY
      setStartY(newY)
    },
    { wait: 500 }
  )

  //  拖拽结束
  const handleTouchEnd = () => {
    Taro.vibrateShort()
    if (dragging === null) return
    // 根据最终位置更新列表顺序
    const targetIndex = Math.round(list[dragging].top / props.itemHeight)
    const newList = [...list]
    const movedItem = newList.splice(dragging, 1)[0]
    newList.splice(targetIndex, 0, movedItem)
    // 重置元素位置
    const arr = newList.map((item, index) => ({ ...item, top: index * props.itemHeight }))
    setList(arr)
    setDragging(null)
    props.onchange(arr)
  }

  return (
    <View className={styles.drag_list}>
      {list.map((item, index) => (
        <View
          className={styles.drag_item}
          key={item.id}
          style={{
            top: `${item.top}px`,
            zIndex: dragging === index ? 999 : 1,
            opacity: dragging === index ? 0.5 : 1
          }}
          onLongPress={(e) => {
            console.log('【长按】', e)
            handleLongPress(e, index)
          }}
          onTouchMove={handleTouchMove}
          onTouchEnd={handleTouchEnd}
        >
          {props.renderItem(item)}
        </View>
      ))}
    </View>
  )
}

export default DragSortList

```js
.drag_list{
  position: relative;
  .drag_item{
    background-color: #fff;
    width: 100%;
    position: absolute;
    left: 0;
    transition: top linear 0.3s;
  }
}
使用
<DragSortList
        list={[
          { id: 1, name: '集美仓' },
          { id: 2, name: '海沧仓' },
          { id: 3, name: '思明仓' },
          { id: 4, name: '湖里仓' }
        ]}
        itemHeight={45}
        renderItem={(item) => (
          <View
            style={{
              height: 40,
              lineHeight: '40px',
              borderBottom: '1px solid #e8e8e8',
              padding: '0 15px'
            }}
          >
            <Icon name={'wap-nav'} /> {item.name}
          </View>
        )}
        onchange={(e) => {
          console.log(e)
        }}
      />
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值