react-sortable-hoc拖拽
react使用react-sortable-hoc实现可多级展开平级拖拽
安装
npm i array-move
npm install react-sortable-hoc --save
设置数据
拖拽设置内容
点击图标展示子集,需要设置distance
拖拽方法
主要代码
const SortableItem = SortableElement(({ value }) => (
<div className={styles.tableList}>
<div className={styles.item}>
{!!value.children && !value.click && (
<PlusOutlined onClick={() => handleIcon(value.id)} className={styles.icon} />)}
{!!value.children && value.click && (
<MinusOutlined onClick={() => handleIcon(value.id)} className={styles.icon} />)}
{value.id}
</div>
<div className={styles.item}>{value.name}</div>
<div className={styles.item}>
<span onClick={() => {}}>修改</span>
<span className={styles.ml20}>删除</span>
</div>
</div>
));
const SortableList = SortableContainer(({ items }) => {
return (
<div>
{items.map((value, index) => (
<div key={index}>
<SortableItem key={`item-${value.id}`} index={index} value={value} />
{!!value.children && value.click && (
<div className={styles.ml20}>
<SortableList
distance={5}
items={value.children}
onSortEnd={e => onSortEnd(e, value.id)} />
</div>)}
</div> ))}
</div>
);
});
/**
* @description:拖拽
* @param {*} e 默认参数
* @param {*} id 每级内容
*/
const onSortEnd = (e, id) => {
// 如果ID为0就是第一级
if (id !== 0) {
// 获取是哪一层级 修改children内容
const newData = JSON.parse(JSON.stringify(data));
const fn = val => {
val.forEach(element => {
if (element.id == id) {
element.children = arrayMoveImmutable(element.children, e.oldIndex, e.newIndex);
} else {
!!element.children && fn(element.children);
}
});
};
fn(newData);
setData(newData);
} else {
setData(arrayMoveImmutable(data, e.oldIndex, e.newIndex));
}
};
可能遇到问题:
- 1.没有样式:例如使用了less的时候样式嵌套,平级写法就可以解决。
- 2.无法点击:设置distance属性
react-sortable-hoc:www.5axxw.com/wiki/conten…
原文链接:https://juejin.cn/post/7221817362143461436 作者:西南以北