【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;
 }

你可能感兴趣的:(javascript,react.js,前端)