【Ant Design】Tree树形控件踩坑记录

基于 React 版

基础用法: 官方文档

坑位props: fieldNames

参数说明类型默认值版本
fieldNames自定义节点 title、key、children 的字段object{ title: title, key: key, children: children }4.17.0

示例:

import { Tree } from 'antd';
import React from 'react';

const treeData = [
    {
        title: 'parent 0',
        id: '0-0',
        children: [
            {
                title: 'leaf 0-0',
                id: '0-0-0',
                isLeaf: true,
            },
            {
                title: 'leaf 0-1',
                id: '0-0-1',
                isLeaf: true,
            },
        ],
    }
];

const App = () => {
  const onSelect = (selectedKeys, info) => {
    console.log('selected', selectedKeys, info);
  };

  const onCheck = (checkedKeys, info) => {
    console.log('onCheck', checkedKeys, info);
  };

  const drawerFieldNames = {
  		title: 'title',
      	key: 'id',
     	children: 'children'
  }

  return (
    <Tree
      checkable
      defaultExpandedKeys={['0-0-0', '0-0-1']}
      defaultSelectedKeys={['0-0-0', '0-0-1']}
      defaultCheckedKeys={['0-0-0', '0-0-1']}
      onSelect={onSelect}
      onCheck={onCheck}
      fieldNames={drawerFieldNames}
      treeData={treeData}
    />
  );
};

export default App;

根据上述示例,我们根据官方文档设定了自定义的字段对应名称,理论上应该按照我们设定的字段对应,但实际执行过程中会出现如下错误:

Warning: Tree node must have a certain key: [undefined]
Warning: Tree node must have a certain key: [undefined > undefined]

解决方案:
服务端/客户端对接数据时,将treeList数据增加上key字段;
例如:

formatBookmarksTreeList(list)
{
     list.map((item)=>{
     	 // 此行是重点
         item.key = item.id;
         if (item['children']){
             item.children = formatBookmarksTreeList(item.children);
         }
         return item;
     });
     return list;
 }
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

陀螺蚁

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值