在 React 中使用 antd 组件中的 treeSelect 组件, 想要在获取当前选中节点的所有子节点. 在使用 onChange 方法的时候, 使用递归方法获得.
- const treeData = [
- {
- title: 'Node1',
- value: '0-0',
- key: '0-0',
- children: [
- {
- title: 'Child Node1',
- value: '0-0-1',
- key: '0-0-1',
- },
- {
- title: 'Child Node2',
- value: '0-0-2',
- key: '0-0-2',
- },
- ],
- },
- {
- title: 'Node2',
- value: '0-1',
- key: '0-1',
- },
- ];
- class TreeChild extends React.Component{
- getChild=(arr)=>{
- let newArr = []
- for(let item = 0;item <arr.length;item++){
- newArr.push(arr[item].props.value)
- if(arr[item].props.children.length>0){
- newArr.push(....getChild(arr[item].props.children))
- }
- }
- return newArr
- }
- onChange=(value, label, extra)=>{
- if(extra.triggerNode){
- let arr = this.getChild(extra.triggerNode.props.children)
- }
- }
- render() {
- return (
- <TreeSelect
- style={{ width: '100%' }}
- treeData={treeData}
- onChange={this.onChange}
- />
- );
- }
- }
就是这样简单, 一开始还琢磨不来递归的写法, 会了就很简单了.
来源: http://www.jianshu.com/p/c72cbcd74c9b