微信小程序拖拽排序写法 MovableView

本文介绍了一个使用JavaScript和CSS实现的可拖动组件,通过监听用户触摸事件调整视图位置,并在移动结束后更新数据结构,确保列表元素顺序的实时变化。关键操作包括移动开始、移动过程中处理和移动结束后的状态更新。

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

<MovableArea className='move-area' style={{ height: `${120 * list.length}px` }} >
    {
        list.map((item, index) => {
            return (
                <MovableView
                    onChange={movchange}
                    onTouchEnd={movend.bind(null ,index)}
                    direction='vertical'
                    className='move-view'
                    x={item.x}
                    y={item.y} // x,y 的值我是在获取list的值时设置的
                    damping={15}
                >
                    <ProductItem
                        productItem = {item}
                        arrayWay = 'transverse'
                    /> //需要移动的单项内容
                </MovableView>
            )
        })
    }
</MovableArea>
/**
 * @Description: 保存移动到的位置
 */
const movchange = (e) => {
       // 防止点击的时候也换序了
    if (e.detail.source === 'touch') {
        saveData.y = e.detail.y
        saveData.source = 'touch'
    } else {
        saveData.source = ''
    }
}

/**
 * @Description: 移动结束
 */
const movend = (index) => {
    if (typeof saveData.y === 'undefined' || saveData.source !== 'touch') {
        return
    }
    let productList = JSON.parse(JSON.stringify(list))
        
    const moveToIndex = Math.round(saveData.y/120) // 我的单个模块高度120 移动后的高度除以120确定我移动到的元素索引
    productList[moveToIndex] = list[index]
    productList[index] = list[moveToIndex]
    setState({
        ...state,
        list: productList
    })
    setTimeout(function(){
        productList.map((item, index) => {
            item.y = 120*index
        })
        setState({
            ...state,
            list: productList
        })
        setCheckArr(productList)
    },100)
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值