使用MovableArea, MovableView
支持节点任意大小,任意拖拽排序
完整代码,复制就可以使用
import React, { useEffect, useState } from "react";
import { MovableArea, MovableView, View } from "@tarojs/components";
export default () => {
const [changeId, setChangeId] = useState();
const [initData, setInitData] = useState([]);
const [dragList, setDragList] = useState([]);
const initMove = () => {
const setY = (index) => {
let y = 0;
let _data = dragList.slice(0, index)
_data.forEach(item => {
y += item.height;
})
y /= 2;
return y
}
setInitData(dragList.map((item, index) => {
if (index) {
item.y = setY(index);
} else {
item.y = 0
}
return item
}))
}
useEffect(() => {
setDragList([
{
id: 0,
height: 100,
color: 'red',
y: 0
},
{
id: 1,
height: 50,
color: 'pink',
y: 0
},
{
id: 2,
height: 200,
color: 'blue',
y: 0
},
{
id: 3,
height: 300,
color: 'gray',
y: 0
}
])
}, [])
useEffect(() => {
let time = setTimeout(() => {
initMove();
}, 1000)
return () => {
clearTimeout(time);
}
}, [dragList])
return (
<>
<MovableArea style='height: 600px; width:350px; background: #00bcd2;'>
{
initData.map((item) => {
return (
<MovableView
onChange={(e) => {
setChangeId(item.id);
setDragList(dragList.map(_item => {
if (_item.id == item.id) {
_item.y = e.detail.y;
}
return _item;
}).sort((a, b) => a.y - b.y));
}}
out-of-bounds
direction='vertical'
animation={false}
y={item.y}
style={{
width: '750rpx',
height: item.height + 'rpx',
backgroundColor: item.color,
zIndex: item.id == changeId ? 2 : 1,
}}>
<View>id: {item.id}</View>
</MovableView>
)
})
}
</MovableArea>
</>
)
}