【问题标题】:Using TreeItemLabel for TreeItem in VSCode Extension在 VSCode 扩展中为 TreeItem 使用 TreeItemLabel
【发布时间】:2021-04-20 18:31:37
【问题描述】:

我正在构建一个 Tree View VSCode 扩展,并希望在某些情况下突出显示我的树项标签的一部分。 TreeItemLabel 似乎通过 highlights 属性支持此功能。

API docs 指定TreeItem 的一个构造函数签名接受TreeItemLabel 作为第一个参数。 docs for TreeItemLabel 仅显示此对象的两个属性(hightlights?label),没有任何构造函数。我对 JS/TS 世界还很陌生,不知道如何将TreeItemLabel“传递”给TreeItem 的构造函数。

我似乎无法从 vscode 命名空间中的任何位置导入 TreeItemLabel,这消除了使用构造函数的可能性。

我发现了一个sample test,它似乎通过显式定义具有这些属性的对象来手动构造一个具有highlights 属性的TreeItem,但我不确定如何将其转换为我的用例。

就我而言,我有一个扩展 TreeItem 的类,并将一些值传递给 super() 以创建 TreeItem:

export class Org extends vscode.TreeItem {
    public readonly contextValue = 'org';

    constructor(
        public readonly name: string,
        public readonly devName: string,
        public readonly tooltip: string, 
        public readonly collapsibleState: vscode.TreeItemCollapsibleState
    ) {
        super(name, collapsibleState);
    }

    iconPath = vscode.ThemeIcon.File;
}

如何将我的呼叫更改为super(),以便我可以使用TreeItemLabel? 提前致谢!

编辑#1:

当我尝试将我想要的属性定义为调用super() 的第一个参数时,如下所示:

constructor(
        // The name displayed in the tree view
        public readonly name: string,
        // The name of the org (without anything extra added)
        public readonly devName: string,
        public readonly tooltip: string, 
        public readonly collapsibleState: vscode.TreeItemCollapsibleState
    ) {
        super({label:name, highlights:[0,2]}, collapsibleState);
    }

我得到以下信息:

No overload matches this call.
  Overload 1 of 2, '(label: string, collapsibleState?: TreeItemCollapsibleState | undefined): TreeItem', gave the following error.
    Argument of type '{ label: string; highlights: number[]; }' is not assignable to parameter of type 'string'.
  Overload 2 of 2, '(resourceUri: Uri, collapsibleState?: TreeItemCollapsibleState | undefined): TreeItem', gave the following error.
    Argument of type '{ label: string; highlights: number[]; }' is not assignable to parameter of type 'Uri'.
      Object literal may only specify known properties, and 'label' does not exist in type 'Uri'.ts(2769)

【问题讨论】:

  • 看起来类构造函数的类型定义与intellisense使用的类型定义不同,当你用new TreeItem(构造TreeItem时,intellisense会告诉你什么

标签: typescript visual-studio-code vscode-extensions


【解决方案1】:

只需定义一个具有您需要的属性的对象。您可能需要根据name 字符串更改数字。

export class Org extends vscode.TreeItem {
    public readonly contextValue = 'org';

    constructor(
        public readonly name: string,
        public readonly devName: string,
        public readonly tooltip: string, 
        public readonly collapsibleState: vscode.TreeItemCollapsibleState
    ) {
        super({label:name, highlights:[[0,5],[9,12]]}, collapsibleState);
    }

    iconPath = vscode.ThemeIcon.File;
}

【讨论】:

  • @Brand0R 我在 JavaScript 扩展中尝试过它,它工作但我不得不更改 highlights 参数(它是一个元组数组)
猜你喜欢
  • 1970-01-01
  • 2017-07-29
  • 1970-01-01
  • 1970-01-01
  • 2017-10-18
  • 2019-08-26
  • 2018-11-17
  • 1970-01-01
  • 2020-10-10
相关资源
最近更新 更多