ant design中的TreeSelect 组件如何只获取子节点的集合?

\#\#\# 题目描述

ant design中的TreeSelect 组件

image.png

选中节点的数据为:

image.png

期望得到的数据为:

['0-0-0','0-1-0','0-1-1']

希望显示方式为:SHOW_PARENT

数据获取格式为:SHOW_CHILD

想要 获取当前选择的所有子节点key,而不包括父节点的key

\#\#\# 题目来源及自己的思路

当前案例可以使用数据筛选, 但是实际项目中数据没有0-0-1这样的规律,

\#\#\# 相关代码
粘贴代码文本(请勿用截图)

codesandbox

import { TreeSelect } from 'antd';

const { SHOW_PARENT } = TreeSelect;

const treeData = [
  {
    title: 'Node1',
    value: '0-0',
    key: '0-0',
    children: [
      {
        title: 'Child Node1',
        value: '0-0-0',
        key: '0-0-0',
      },
    ],
  },
  {
    title: 'Node2',
    value: '0-1',
    key: '0-1',
    children: [
      {
        title: 'Child Node3',
        value: '0-1-0',
        key: '0-1-0',
      },
      {
        title: 'Child Node4',
        value: '0-1-1',
        key: '0-1-1',
      },
      {
        title: 'Child Node5',
        value: '0-1-2',
        key: '0-1-2',
      },
    ],
  },
];

class Demo extends React.Component {
  state = {
    value: ['0-0-0'],
  };

  onChange = value => {
    console.log('onChange ', value);
    this.setState({ value });
  };

  render() {
    const tProps = {
      treeData,
      value: this.state.value,
      onChange: this.onChange,
      treeCheckable: true,
      showCheckedStrategy: SHOW_PARENT,
      placeholder: 'Please select',
      style: {
        width: '100%',
      },
    };
    return <TreeSelect {...tProps} />;
  }
}

ReactDOM.render(<Demo />, mountNode);

and design TreeSelect 地址

阅读 12.9k
2 个回答

加上treeCheckable属性就行

https://codesandbox.io/s/kego...


不要showCheckedStrategy: SHOW_PARENT,使用他的默认值!!!你仔细看看这个API。


根据treeDataSimpleMode属性把你的树形结构定义成简单的结构,然后使用showCheckedStrategy: SHOW_PARENT,全选时只显示父节点。
最后根据选择出来的数据,根据isLeaf判断节点A是否叶子节点,不是的话,就遍历treeDatapId=A.id的所有节点。

onchange: function(value, label, extra)

第三个参数,extra.allCheckedNodes 包含所选择所有参数, 分析这个数据结构,通过递归获取到所有的子项:

  const getvaluechild = (arr) => {
    let newArr = []
    for (let i = 0; i < arr.length; i++) {
      if (arr[i].children.length > 0) {
        newArr.push(...getvaluechild(arr[i].children))
      } else {
        newArr.push(arr[i].node.key)
      }
    }
    return newArr
  }

以上,能用.

会有一个Warning: allCheckedNodes is deprecated

再看看大家有什么方法, 或者准备看下源码中SHOW_CHILD的实现.

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题