Hi, I'm Alan

react可拖动的好用的树结构插件

react tree 可拖动树结构:

hexagon

github地址:

github地址:react-sortable-tree

安装:

NPM

npm install react-sortable-tree –save

YARN

yarn add react-sortable-tree

引用

import SortableTree from ‘react-sortable-tree’;
import ‘react-sortable-tree/style.css’;

使用

此处我是做成可公共组件props可传data数据调用的公用组件.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
export default class SortableTrees extends React.PureComponent {
// 定义propTypes传输类型:
static propTypes = {
isDrop: PropTypes.bool, // 是否可以拖动
treeData: PropTypes.array, // 树结构数据
onChangeVal: PropTypes.func, // 值改变触发事件
haveChildren: PropTypes.bool, // 是否有子级
};

// 设置默认值
static defaultProps = {
isDrop: true,
haveChildren: true,
treeData: [{
title: 'Workflow test',
expanded: true,
children: [{
title: 'taskflow test',
}, {
title: 'taskflow test1',
expanded: true,
children: [{
title: 'taskflow2-1',
}, {
title: 'taskflow2-2',
}],
}],
}],
onChangeVal: () => {},
};

//调用组件时,值发生改变接收新的数据
onChangeValue = (treeData) => {
this.props.onChangeVal(JSON.stringify(treeData));
}

//是否可以拖动(默认可以不添加, 根据需求而定)
stopParentNode = (node) => {
if (!node.nextParent) {
return false;
}
return true;
}

//是否有子级(默认可以不添加, 根据需求而定)
toHaveChildren = (node) => {
if (node.type === 'streaming') {
return false;
}
return true;
}

// render
render() {
const {
isDrop,
treeData,
haveChildren,
} = this.props;
return (
<SortableTree
treeData={treeData}
onChange={(e) => { this.onChangeValue(e); }}
canDrop={isDrop ? this.stopParentNode : () => { return false; }}
canNodeHaveChildren={haveChildren ? this.toHaveChildren : () => { return false; }}
/>
);
}
}

外部调用此组件

1
2
3
4
<SortableTrees
treeData={treeData} // treeData是你自己的数据
onChangeVal={(treeDatas) => { this.setTreeData(treeDatas); }}
/>

Props 参数

treeData (object): 树结构数据

onChange (func): 数据发生改变时触发(例如:拖动)

getNodeKey (func): 数据更改时,得到node节点

generateNodeProps (func): 添加自定义结构

onMoveNode (func): 移动node触发

onVisibilityToggle (func): 子节点收起或展开时触发

onDragStateChanged (func): 拖动开始或结束时调用

maxDepth (number): 可以插入最大深度节点。 默认为无限

rowDirection (string): 行方向

canDrag (func or bool): 是否禁止拖动

canDrop: (func): 返回false以防止节点掉入给定位置

canNodeHaveChildren: (func): 是否有自己功能

theme (object): 主题风格

searchMethod (func): 搜索功能

className (string): class

rowHeight (number or func): 行高

---- 感谢观看 :thank you: ----