更改活动选项卡(Typescript)

3htmauhk  于 2023-03-09  发布在  TypeScript
关注(0)|答案(1)|浏览(152)

我有一个选项卡数组。
下面是代码

const navTabs: ITab[] = [
    { Name: allTab, Icon: 'gs-all', Selected: true },
    { Name: sources.corporateResources, Icon: 'gs-resources', Selected: false },
    { Name: sources.employee, Icon: 'gs-people', Selected: false },
    { Name: sources.services, Icon: 'gs-services', Selected: false },
    { Name: sources.information, Icon: 'gs-docs', Selected: false },
    { Name: sources.tableau, Icon: 'gs-tableau', Selected: false },
];

在方法激活选项卡中,我将selected: true选项卡更改为false,然后按名称查找选项卡并将其设置为selected: true
下面是代码

public activateTab(name: TabName): void {
    this.activeTab = name;
    this.navTabs.find(x => x.Selected === true).Selected = false;
    this.navTabs.find(x => x.Name === name).Selected = true;
    // console.log(navTabs);
}

我能一次做好吗?

this.navTabs.find(x => x.Selected === true).Selected = false;
this.navTabs.find(x => x.Name === name).Selected = true;
f4t66c6m

f4t66c6m1#

您可以循环遍历所有这些变量(forEach),然后将Selected设置为选中name的条件:

const navTabs = [
  { Name: 'foo', Icon: 'gs-all', Selected: true },
  { Name: 'foo', Icon: 'gs-resources', Selected: false },
  { Name: 'foo', Icon: 'gs-people', Selected: false },
  { Name: 'bar', Icon: 'gs-services', Selected: false },
  { Name: 'foo', Icon: 'gs-docs', Selected: false },
  { Name: 'foo', Icon: 'gs-tableau', Selected: false },
];

const nameToMatch = 'bar';

navTabs.forEach(o => o.Selected = (o.Name === nameToMatch));

console.log(navTabs);

相关问题