做树组件的时候有一个需求, 在请求详情页面的时候自动展开勾选的树节点, 如下:
屏幕快照 2019-08-07 上午 9.26.55.PNG
下面来说一下实现这个过程的思路:
1. 在请求详情页面的时候要拿到选中的 key 的数组 (一般都是后台返给的)
2. 设置 expandKeys 属性, 将数组赋值给 expandKeys;
3. 还需要加入 onExpand 事件和 autoExpandParent 属性, 如果只有 expandKeys 没有 onExpand 事件, 则出现的情况是值能显示出来展开的 Tree, 但是点展开功能的时候无反应; autoExpandParent 属性是子节点关闭的时候, 父节点也能关闭
下面我们就按照这个步骤走:
- state = {
- expandedKeys: [],
- autoExpandParent: true,
- };
- // 赋值
- getRoleInfo = () => {
- get_department_info({ id: Id }).then(res => {
- let data = res.data.responseData;
- this.setState({
- expandedKeys: data.parentIds // 这步骤把数据存放在 depExpandKeys 变量中
- })
- });
- };
- // 展开方法
- onExpand = expandedKeys => {
- this.setState({
- expandedKeys,
- autoExpandParent: false,
- });
- };
- <Tree
- checkable
- onExpand={this.onExpand}
- expandedKeys={this.state.expandedKeys}
- autoExpandParent={this.state.autoExpandParent}
- onCheck={this.onCheck}
- checkedKeys={this.state.checkedKeys}
- >
- {this.renderTreeNodes(treeData)}
- </Tree>
这样就 OK 了~
来源: http://www.jianshu.com/p/100b89c7093e