官方文档
clauderic.github.io/react-sorta…
文档中有具体实现效果,我只举例最简单的实现方法,更复杂的小伙伴可以直接参考文档实现。
具体实现
安装
npm install react-sortable-hoc
npm install array-move
全部代码
import React, { useState } from 'react';
import { SortableContainer, SortableElement } from 'react-sortable-hoc';
import { arrayMoveImmutable } from 'array-move';
// 设置排序组件
const SortableItem = SortableElement(({ value }) => {
return (
<div style={{zIndex: 99999}}>
<div>{value.index + 1}、{value.value}</div>
</div>
)
});
const SortableList = SortableContainer(({ items }) => {
return (
<div>
{items.map((value, index) => (
<SortableItem key={index} index={index} value={{value, index}} />
))}
</div>
);
});
function TestSortArray() {
const [items, setItems] = useState(['你', '是', '不是', '哈哈', '哒哒哒']);
const onSortEnd = ({ oldIndex, newIndex }) => {
setItems(arrayMoveImmutable(items, oldIndex, newIndex)); //获得新旧两个index,将数组进行修改
};
return (
<SortableList items={items} onSortEnd={onSortEnd} />
)
}
export default TestSortArray;