You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Ant Design Tree组件的ref变量应使用什么TypeScript类型?

在TypeScript中为Ant Design Tree组件的ref指定正确类型

当你在TypeScript环境下使用Ant Design的Tree组件时,直接调用useRef()会触发类型不兼容的报错,错误提示如下:

Type 'MutableRefObject' is not assignable to type 'Ref<Tree> | undefined'.
Type 'MutableRefObject' is not assignable to type 'RefObject<Tree>'.
Types of property 'current' are incompatible.
Type 'undefined' is not assignable to type 'Tree | null'. ts(2322)
index.d.ts(246, 9): The expected type comes from property 'ref' which is declared here on type 'IntrinsicAttributes & TreeProps & { children?: ReactNode; } & RefAttributes<Tree>'

正确的类型指定方式

你需要为useRef明确指定泛型类型,类型为Tree<DataNode> | null,同时将初始值设为null,代码示例如下:

import { Tree, DataNode } from 'antd';
import { useRef, FunctionComponent } from 'react';

const SomeTree: FunctionComponent = () => {
  // 指定ref的类型为Tree<DataNode> | null,初始值设为null
  const treeRef = useRef<Tree<DataNode> | null>(null);
  // treeData需符合DataNode[]类型
  const treeData: DataNode[] = [/* 你的树形数据 */];

  return (
    <Tree
      showLine
      treeData={treeData}
      ref={treeRef}
    />
  );
};

自定义节点类型的情况

如果你的树形节点是自定义扩展类型,只需将泛型替换为自定义的节点类型即可:

import { Tree, DataNode } from 'antd';
import { useRef, FunctionComponent } from 'react';

// 自定义节点类型,继承DataNode
interface CustomTreeNode extends DataNode {
  customField: string;
}

const SomeTree: FunctionComponent = () => {
  const treeRef = useRef<Tree<CustomTreeNode> | null>(null);
  const treeData: CustomTreeNode[] = [
    {
      title: '自定义节点',
      key: '1',
      customField: '自定义字段内容'
    }
  ];

  return (
    <Tree<CustomTreeNode>
      showLine
      treeData={treeData}
      ref={treeRef}
    />
  );
};

报错原因说明

默认调用useRef()时,TS会推断其类型为MutableRefObject<undefined>,但Tree组件的ref要求current属性的类型为Tree<DataNode> | null,两者类型不匹配才会触发报错。通过明确指定泛型类型并设置初始值为null,就能让TS通过类型检查。

内容的提问来源于stack exchange,提问作者Deepak Oli

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.28 17:12:49