做树组件的时候有一个需求,在请求详情页面的时候自动展开勾选的树节点,如下:
屏幕快照 2019-08-07 上午9.26.55.png
下面来说一下实现这个过程的思路:
1.在请求详情页面的时候要拿到选中的key的数组(一般都是后台返给的)
2.设置expandKeys属性,将数组赋值给expandKeys;
3.还需要加入onExpand事件和autoExpandParent属性
注意⚠️:如果只有expandKeys没有onExpand事件,则出现的情况是值能显示出来展开的Tree,但是点展开功能的时候无反应;autoExpandParent属性是:是否自动展开父节点,如果为true的话,关闭展开功能失效,所以要在onExpand的时候让这个属性变为false
下面我们就按照这个步骤走:
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了~