syncfusion-react-tabs

Compare original and translation side by side

🇺🇸

Original

English
🇨🇳

Translation

Chinese

Implementing Tabs in Syncfusion React

在Syncfusion React中实现Tab组件

The Tab component organizes related content into tabbed sections with headers, allowing users to switch between views. This comprehensive skill guides you through setup, customization, content rendering strategies, API methods, events, accessibility, animations, persistence, and advanced features like drag-and-drop reordering.
Tab组件将相关内容组织到带标题的选项卡区域中,允许用户在不同视图间切换。本技能全面指导你完成组件的设置、自定义、内容渲染策略、API方法、事件处理、无障碍支持、动画效果、状态持久化以及拖放重排序等高级功能的实现。

Table of Contents

目录

When to Use This Skill

何时使用此技能

  • Creating tabbed interfaces with header-based navigation
  • Organizing content into logical sections or views
  • Building responsive layouts with scrollable or popup overflow handling
  • Customizing header styling and icon positioning
  • Managing content rendering performance (lazy loading, dynamic, or initial render)
  • Implementing drag-and-drop tab reordering for user customization
  • Adding localization support for international applications
  • Ensuring accessibility compliance (WCAG, ARIA, keyboard navigation)
  • Styling tabs with custom CSS or theme customization
  • Programmatically managing tabs (add, remove, select, hide/show)
  • Handling tab-related events (selection, drag-drop, add, remove)
  • Preserving user preferences with state persistence
  • Implementing smooth animations and transitions
  • 创建基于标题导航的选项卡界面
  • 将内容组织为逻辑分段或视图
  • 构建带滚动或弹出式溢出处理的响应式布局
  • 自定义标题样式和图标位置
  • 优化内容渲染性能(懒加载、动态渲染或初始渲染)
  • 实现拖放选项卡重排序以支持用户自定义
  • 为国际化应用添加本地化支持
  • 确保无障碍合规性(WCAG、ARIA、键盘导航)
  • 通过自定义CSS或主题定制选项卡样式
  • 以编程方式管理选项卡(添加、删除、选择、显示/隐藏)
  • 处理选项卡相关事件(选择、拖放、添加、删除)
  • 通过状态持久化保存用户偏好
  • 实现流畅的动画与过渡效果

Component Overview

组件概述

The Tab component is a navigation control that displays content organized into tabs. Each tab has a header and associated content. Tabs support:
  • Multiple header positions (top, bottom, left, right)
  • Overflow handling (scrollable navigation or popup mode)
  • Flexible content rendering (on-demand, dynamic, or initial load)
  • Drag-and-drop reordering for interactive tab management
  • Full accessibility with ARIA attributes and keyboard navigation
  • Extensive customization via CSS and theme options
  • Internationalization through localization APIs
  • Animation effects for content transitions
  • State persistence across page reloads
  • HTML sanitization for security
Tab组件是一个导航控件,用于显示按选项卡组织的内容。每个选项卡包含一个标题和对应的内容区域。Tab组件支持:
  • 多种标题位置(顶部、底部、左侧、右侧)
  • 溢出处理(滚动式导航或弹出模式)
  • 灵活的内容渲染方式(按需渲染、动态渲染或初始加载)
  • 拖放重排序,支持交互式选项卡管理
  • 完整的无障碍支持,包含ARIA属性和键盘导航
  • 通过CSS和主题选项实现广泛自定义
  • 通过本地化API实现国际化
  • 内容过渡动画效果
  • 跨页面重载的状态持久化
  • HTML内容清理以保障安全

Documentation and Navigation Guide

文档与导航指南

Getting Started

入门指南

📄 Read: references/getting-started.md
  • Package dependencies and installation
  • Vite and Create React App setup
  • CSS imports and theme configuration
  • Basic tab initialization with JSON items
  • Minimal working example and running the app
When to read: Start here to set up a basic Tab component in your React application.
📄 阅读: references/getting-started.md
  • 包依赖与安装
  • Vite和Create React App项目设置
  • CSS导入与主题配置
  • 使用JSON项初始化基础Tab组件
  • 最小可运行示例与应用启动
阅读时机: 从这里开始,在你的React应用中设置基础Tab组件。

Header Styling & Customization

标题样式与自定义

📄 Read: references/header-styling.md
  • Built-in header style classes (e-fill, e-background, e-accent)
  • Icon positioning options (left, right, top, bottom)
  • Icon and header customization with CSS classes
  • Code examples for styled headers
  • Styling content and hover states
When to read: Use this when you need to customize tab header appearance, add icons, or apply predefined styles.
📄 阅读: references/header-styling.md
  • 内置标题样式类(e-fill、e-background、e-accent)
  • 图标位置选项(左、右、上、下)
  • 通过CSS类自定义图标和标题
  • 带样式标题的代码示例
  • 内容与悬停状态样式定制
阅读时机: 当你需要自定义选项卡标题外观、添加图标或应用预定义样式时使用。

Orientation & Overflow Modes

方向与溢出模式

📄 Read: references/orientation-overflow.md
  • Header placement positions (top, bottom, left, right)
  • Scrollable mode with navigation arrows
  • Popup mode with dropdown display
  • Touch and swipe support
  • Width constraints and responsive behavior
When to read: Use this when you need to control header position, handle many tabs with overflow, or build responsive layouts.
📄 阅读: references/orientation-overflow.md
  • 标题放置位置(顶部、底部、左侧、右侧)
  • 带导航箭头的滚动模式
  • 下拉弹出模式
  • 触摸与滑动支持
  • 宽度约束与响应式行为
阅读时机: 当你需要控制标题位置、处理大量选项卡的溢出问题或构建响应式布局时使用。

Content Rendering Strategies

内容渲染策略

📄 Read: references/content-rendering.md
  • On-demand rendering (lazy loading, default mode)
  • Dynamic rendering for state-isolated tabs
  • Initial rendering for state preservation
  • Performance vs. state considerations
  • Choosing the right rendering mode
When to read: Use this to optimize tab content performance or preserve user interactions across tab switches.
📄 阅读: references/content-rendering.md
  • 按需渲染(懒加载,默认模式)
  • 用于状态隔离选项卡的动态渲染
  • 用于状态保留的初始渲染
  • 性能与状态的权衡考量
  • 选择合适的渲染模式
阅读时机: 用于优化选项卡内容性能,或在选项卡切换时保留用户交互状态。

Drag and Drop Reordering

拖放重排序

📄 Read: references/drag-drop-reordering.md
  • Enabling drag-and-drop with allowDragAndDrop
  • Handling drag events (onDragStart, dragging, dragged)
  • Preventing drag/drop for specific items
  • Tab-to-tab drag and drop
  • Dragging tabs to external sources (TreeView)
  • Drag area constraints
When to read: Use this to allow users to reorder tabs or integrate tab dragging with other components.
📄 阅读: references/drag-drop-reordering.md
  • 通过allowDragAndDrop启用拖放功能
  • 处理拖放事件(onDragStart、dragging、dragged)
  • 禁止特定选项卡的拖放操作
  • 选项卡间的拖放
  • 将选项卡拖放到外部组件(如TreeView)
  • 拖放区域约束
阅读时机: 当你需要允许用户重新排序选项卡,或集成选项卡拖放与其他组件时使用。

Accessibility & Localization

无障碍与本地化

📄 Read: references/accessibility-localization.md
  • WCAG 2.2 and Section 508 compliance
  • ARIA attributes and roles for tabs
  • Keyboard navigation (arrows, Home, End, Enter, Escape)
  • Screen reader support
  • Localization with L10n class
  • Right-to-left (RTL) language support
When to read: Use this when building accessible applications or supporting multiple languages.
📄 阅读: references/accessibility-localization.md
  • WCAG 2.2和Section 508合规性
  • 选项卡的ARIA属性与角色
  • 键盘导航(箭头键、Home、End、Enter、Escape)
  • 屏幕阅读器支持
  • 通过L10n类实现本地化
  • 从右到左(RTL)语言支持
阅读时机: 当你构建无障碍应用或支持多语言时使用。

Quick Start Example

快速入门示例

Here's a minimal Tab component setup:
jsx
import React from 'react';
import { TabComponent, TabItemsDirective, TabItemDirective } from '@syncfusion/ej2-react-navigations';
import '@syncfusion/ej2-base/styles/tailwind3.css';
import '@syncfusion/ej2-buttons/styles/tailwind3.css';
import '@syncfusion/ej2-popups/styles/tailwind3.css';
import '@syncfusion/ej2-react-navigations/styles/tailwind3.css';

export default function TabExample() {
  const tabItems = [
    {
      header: { text: 'Home' },
      content: 'Welcome to the home tab'
    },
    {
      header: { text: 'Profile' },
      content: 'User profile information'
    },
    {
      header: { text: 'Settings' },
      content: 'Application settings'
    }
  ];

  return (
    <TabComponent>
      <TabItemsDirective>
        {tabItems.map((item, index) => (
          <TabItemDirective key={index} header={item.header} content={item.content} />
        ))}
      </TabItemsDirective>
    </TabComponent>
  );
}
以下是一个最小化的Tab组件设置示例:
jsx
import React from 'react';
import { TabComponent, TabItemsDirective, TabItemDirective } from '@syncfusion/ej2-react-navigations';
import '@syncfusion/ej2-base/styles/tailwind3.css';
import '@syncfusion/ej2-buttons/styles/tailwind3.css';
import '@syncfusion/ej2-popups/styles/tailwind3.css';
import '@syncfusion/ej2-react-navigations/styles/tailwind3.css';

export default function TabExample() {
  const tabItems = [
    {
      header: { text: 'Home' },
      content: 'Welcome to the home tab'
    },
    {
      header: { text: 'Profile' },
      content: 'User profile information'
    },
    {
      header: { text: 'Settings' },
      content: 'Application settings'
    }
  ];

  return (
    <TabComponent>
      <TabItemsDirective>
        {tabItems.map((item, index) => (
          <TabItemDirective key={index} header={item.header} content={item.content} />
        ))}
      </TabItemsDirective>
    </TabComponent>
  );
}

Common Patterns

常见模式

Pattern 1: Styled Tabs with Icons

模式1:带图标的样式化选项卡

jsx
<TabComponent className="e-fill">
  <TabItemsDirective>
    <TabItemDirective 
      header={{ text: 'Home', iconCss: 'e-icons e-home' }} 
      content="Home content" 
    />
    <TabItemDirective 
      header={{ text: 'Profile', iconCss: 'e-icons e-user' }} 
      content="Profile content" 
    />
  </TabItemsDirective>
</TabComponent>
jsx
<TabComponent className="e-fill">
  <TabItemsDirective>
    <TabItemDirective 
      header={{ text: 'Home', iconCss: 'e-icons e-home' }} 
      content="Home content" 
    />
    <TabItemDirective 
      header={{ text: 'Profile', iconCss: 'e-icons e-user' }} 
      content="Profile content" 
    />
  </TabItemsDirective>
</TabComponent>

Pattern 2: Vertical Tabs on the Left

模式2:左侧垂直选项卡

jsx
<TabComponent headerPlacement="Left">
  <TabItemsDirective>
    <TabItemDirective header={{ text: 'Tab 1' }} content="Content 1" />
    <TabItemDirective header={{ text: 'Tab 2' }} content="Content 2" />
  </TabItemsDirective>
</TabComponent>
jsx
<TabComponent headerPlacement="Left">
  <TabItemsDirective>
    <TabItemDirective header={{ text: 'Tab 1' }} content="Content 1" />
    <TabItemDirective header={{ text: 'Tab 2' }} content="Content 2" />
  </TabItemsDirective>
</TabComponent>

Pattern 3: Lazy-Loaded Content (Default)

模式3:懒加载内容(默认)

jsx
<TabComponent>
  <TabItemsDirective>
    <TabItemDirective 
      header={{ text: 'Lazy Tab' }} 
      content={() => <ExpensiveComponent />} 
    />
  </TabItemsDirective>
</TabComponent>
jsx
<TabComponent>
  <TabItemsDirective>
    <TabItemDirective 
      header={{ text: 'Lazy Tab' }} 
      content={() => <ExpensiveComponent />} 
    />
  </TabItemsDirective>
</TabComponent>

Pattern 4: Draggable Tabs

模式4:可拖动选项卡

jsx
<TabComponent allowDragAndDrop={true}>
  <TabItemsDirective>
    <TabItemDirective header={{ text: 'Tab 1' }} content="Content 1" />
    <TabItemDirective header={{ text: 'Tab 2' }} content="Content 2" />
  </TabItemsDirective>
</TabComponent>
jsx
<TabComponent allowDragAndDrop={true}>
  <TabItemsDirective>
    <TabItemDirective header={{ text: 'Tab 1' }} content="Content 1" />
    <TabItemDirective header={{ text: 'Tab 2' }} content="Content 2" />
  </TabItemsDirective>
</TabComponent>

Key Properties Overview

关键属性概述

PropertyTypeDefaultPurpose
headerPlacement
String
'Top'
Position of tab headers:
Top
,
Bottom
,
Left
,
Right
overflowMode
String
'Scrollable'
Overflow handling:
Scrollable
or
Popup
loadOn
String
'Demand'
Content rendering:
Demand
,
Dynamic
, or
Init
allowDragAndDrop
Boolean
false
Enable tab reordering via drag and drop
showCloseButton
Boolean
false
Display close button on tab headers
locale
String
'en-US'
Localization culture code (e.g.,
'fr-FR'
)
width
String/Number
'100%'
Tab container width
height
String/Number
'auto'
Tab container height
heightAdjustMode
String
'Content'
Height adjustment mode:
None
,
Auto
,
Content
,
Fill
selectedItem
Number
0
Index of the active tab
enablePersistence
Boolean
false
Persist selected tab state across reloads
enableHtmlSanitizer
Boolean
true
Sanitize HTML content for security
cssClass
String
''
Custom CSS classes to apply to component
enableRtl
Boolean
false
Enable right-to-left layout
scrollStep
Number
null
Distance to scroll when using scroll arrows
reorderActiveTab
Boolean
true
Reorder to show active tab in header area
clearTemplates
Boolean
true
Clear templates when items change dynamically
dragArea
String
null
Restrict drag area for tab reordering
swipeMode
String
'Both'
Swipe detection:
Both
,
Touch
,
Mouse
,
None
animation
TabAnimationSettingsModelDefaultAnimation settings for tab transitions
属性类型默认值用途
headerPlacement
String
'Top'
选项卡标题位置:
Top
Bottom
Left
Right
overflowMode
String
'Scrollable'
溢出处理方式:
Scrollable
Popup
loadOn
String
'Demand'
内容渲染模式:
Demand
Dynamic
Init
allowDragAndDrop
Boolean
false
启用选项卡拖放重排序
showCloseButton
Boolean
false
在选项卡标题上显示关闭按钮
locale
String
'en-US'
本地化文化代码(例如
'fr-FR'
width
String/Number
'100%'
选项卡容器宽度
height
String/Number
'auto'
选项卡容器高度
heightAdjustMode
String
'Content'
高度调整模式:
None
Auto
Content
Fill
selectedItem
Number
0
激活选项卡的索引
enablePersistence
Boolean
false
跨页面重载持久化选中选项卡的状态
enableHtmlSanitizer
Boolean
true
清理HTML内容以保障安全
cssClass
String
''
应用到组件的自定义CSS类
enableRtl
Boolean
false
启用从右到左布局
scrollStep
Number
null
点击滚动箭头时的滚动距离
reorderActiveTab
Boolean
true
重排序时将激活选项卡显示在标题区域内
clearTemplates
Boolean
true
动态修改选项卡项时清理模板
dragArea
String
null
限制选项卡重排序的拖放区域
swipeMode
String
'Both'
滑动检测模式:
Both
Touch
Mouse
None
animation
TabAnimationSettingsModel默认值选项卡过渡动画设置

Methods & API Reference

方法与API参考

addTab(items, index)

addTab(items, index)

Adds new items to the Tab component. The items are inserted at the specified index.
Parameters:
  • items
    - Array of
    TabItemModel
    objects to add
  • index
    (optional) - Position where items should be inserted. Default is 0.
Returns:
void
Example:
jsx
import React, { useRef } from 'react';
import { TabComponent, TabItemsDirective, TabItemDirective } from '@syncfusion/ej2-react-navigations';

export default function AddTabExample() {
  const tabRef = useRef(null);

  const handleAddTab = () => {
    const newItems = [
      {
        header: { text: 'New Tab' },
        content: 'This is dynamically added content'
      }
    ];
    // Add at the end (index 2 if there are 2 existing tabs)
    tabRef.current.addTab(newItems, 2);
  };

  return (
    <div>
      <button onClick={handleAddTab}>Add Tab</button>
      <TabComponent ref={tabRef}>
        <TabItemsDirective>
          <TabItemDirective header={{ text: 'Tab 1' }} content="Content 1" />
          <TabItemDirective header={{ text: 'Tab 2' }} content="Content 2" />
        </TabItemsDirective>
      </TabComponent>
    </div>
  );
}
向Tab组件添加新选项卡项,插入到指定索引位置。
参数:
  • items
    - 要添加的
    TabItemModel
    对象数组
  • index
    (可选)- 插入位置,默认值为0
返回值:
void
示例:
jsx
import React, { useRef } from 'react';
import { TabComponent, TabItemsDirective, TabItemDirective } from '@syncfusion/ej2-react-navigations';

export default function AddTabExample() {
  const tabRef = useRef(null);

  const handleAddTab = () => {
    const newItems = [
      {
        header: { text: 'New Tab' },
        content: 'This is dynamically added content'
      }
    ];
    // 添加到末尾(如果已有2个选项卡,则索引为2)
    tabRef.current.addTab(newItems, 2);
  };

  return (
    <div>
      <button onClick={handleAddTab}>Add Tab</button>
      <TabComponent ref={tabRef}>
        <TabItemsDirective>
          <TabItemDirective header={{ text: 'Tab 1' }} content="Content 1" />
          <TabItemDirective header={{ text: 'Tab 2' }} content="Content 2" />
        </TabItemsDirective>
      </TabComponent>
    </div>
  );
}

removeTab(index)

removeTab(index)

Removes a tab item at the specified index.
Parameters:
  • index
    - The index of the tab to remove
Returns:
void
Example:
jsx
import React, { useRef } from 'react';
import { TabComponent, TabItemsDirective, TabItemDirective } from '@syncfusion/ej2-react-navigations';

export default function RemoveTabExample() {
  const tabRef = useRef(null);

  const handleRemoveTab = (tabIndex) => {
    tabRef.current.removeTab(tabIndex);
  };

  return (
    <div>
      <button onClick={() => handleRemoveTab(1)}>Remove Tab 2</button>
      <TabComponent ref={tabRef} showCloseButton={true}>
        <TabItemsDirective>
          <TabItemDirective header={{ text: 'Tab 1' }} content="Content 1" />
          <TabItemDirective header={{ text: 'Tab 2' }} content="Content 2" />
          <TabItemDirective header={{ text: 'Tab 3' }} content="Content 3" />
        </TabItemsDirective>
      </TabComponent>
    </div>
  );
}
移除指定索引位置的选项卡项。
参数:
  • index
    - 要移除的选项卡索引
返回值:
void
示例:
jsx
import React, { useRef } from 'react';
import { TabComponent, TabItemsDirective, TabItemDirective } from '@syncfusion/ej2-react-navigations';

export default function RemoveTabExample() {
  const tabRef = useRef(null);

  const handleRemoveTab = (tabIndex) => {
    tabRef.current.removeTab(tabIndex);
  };

  return (
    <div>
      <button onClick={() => handleRemoveTab(1)}>Remove Tab 2</button>
      <TabComponent ref={tabRef} showCloseButton={true}>
        <TabItemsDirective>
          <TabItemDirective header={{ text: 'Tab 1' }} content="Content 1" />
          <TabItemDirective header={{ text: 'Tab 2' }} content="Content 2" />
          <TabItemDirective header={{ text: 'Tab 3' }} content="Content 3" />
        </TabItemsDirective>
      </TabComponent>
    </div>
  );
}

select(args, event)

select(args, event)

Selects a tab by index or DOM element. Programmatically switches to a different tab.
Parameters:
  • args
    - Index (number) or HTMLElement of the tab to select
  • event
    (optional) - DOM event object
Returns:
void
Example:
jsx
import React, { useRef } from 'react';
import { TabComponent, TabItemsDirective, TabItemDirective } from '@syncfusion/ej2-react-navigations';

export default function SelectTabExample() {
  const tabRef = useRef(null);

  const handleSelectTab = (index) => {
    tabRef.current.select(index);
  };

  return (
    <div>
      <div>
        <button onClick={() => handleSelectTab(0)}>Select Tab 1</button>
        <button onClick={() => handleSelectTab(1)}>Select Tab 2</button>
        <button onClick={() => handleSelectTab(2)}>Select Tab 3</button>
      </div>
      <TabComponent ref={tabRef}>
        <TabItemsDirective>
          <TabItemDirective header={{ text: 'Tab 1' }} content="Content 1" />
          <TabItemDirective header={{ text: 'Tab 2' }} content="Content 2" />
          <TabItemDirective header={{ text: 'Tab 3' }} content="Content 3" />
        </TabItemsDirective>
      </TabComponent>
    </div>
  );
}
通过索引或DOM元素选择选项卡,以编程方式切换到不同选项卡。
参数:
  • args
    - 要选择的选项卡索引(数字)或DOM元素
  • event
    (可选)- DOM事件对象
返回值:
void
示例:
jsx
import React, { useRef } from 'react';
import { TabComponent, TabItemsDirective, TabItemDirective } from '@syncfusion/ej2-react-navigations';

export default function SelectTabExample() {
  const tabRef = useRef(null);

  const handleSelectTab = (index) => {
    tabRef.current.select(index);
  };

  return (
    <div>
      <div>
        <button onClick={() => handleSelectTab(0)}>Select Tab 1</button>
        <button onClick={() => handleSelectTab(1)}>Select Tab 2</button>
        <button onClick={() => handleSelectTab(2)}>Select Tab 3</button>
      </div>
      <TabComponent ref={tabRef}>
        <TabItemsDirective>
          <TabItemDirective header={{ text: 'Tab 1' }} content="Content 1" />
          <TabItemDirective header={{ text: 'Tab 2' }} content="Content 2" />
          <TabItemDirective header={{ text: 'Tab 3' }} content="Content 3" />
        </TabItemsDirective>
      </TabComponent>
    </div>
  );
}

enableTab(index, value)

enableTab(index, value)

Enables or disables a specific tab item. Disabled tabs cannot be selected but remain visible.
Parameters:
  • index
    - Index of the tab to enable/disable
  • value
    - Boolean.
    true
    to enable,
    false
    to disable
Returns:
void
Example:
jsx
import React, { useRef } from 'react';
import { TabComponent, TabItemsDirective, TabItemDirective } from '@syncfusion/ej2-react-navigations';

export default function EnableTabExample() {
  const tabRef = useRef(null);

  const toggleTabEnabled = (index) => {
    const isCurrentlyEnabled = !tabRef.current.items[index].isDisabled;
    tabRef.current.enableTab(index, isCurrentlyEnabled);
  };

  return (
    <div>
      <button onClick={() => toggleTabEnabled(1)}>Toggle Tab 2 Enable</button>
      <TabComponent ref={tabRef}>
        <TabItemsDirective>
          <TabItemDirective header={{ text: 'Tab 1' }} content="Content 1" />
          <TabItemDirective header={{ text: 'Tab 2' }} content="Content 2" />
          <TabItemDirective header={{ text: 'Tab 3' }} content="Content 3" />
        </TabItemsDirective>
      </TabComponent>
    </div>
  );
}
启用或禁用指定的选项卡项。禁用的选项卡无法被选中,但仍保持可见。
参数:
  • index
    - 要启用/禁用的选项卡索引
  • value
    - 布尔值,
    true
    表示启用,
    false
    表示禁用
返回值:
void
示例:
jsx
import React, { useRef } from 'react';
import { TabComponent, TabItemsDirective, TabItemDirective } from '@syncfusion/ej2-react-navigations';

export default function EnableTabExample() {
  const tabRef = useRef(null);

  const toggleTabEnabled = (index) => {
    const isCurrentlyEnabled = !tabRef.current.items[index].isDisabled;
    tabRef.current.enableTab(index, isCurrentlyEnabled);
  };

  return (
    <div>
      <button onClick={() => toggleTabEnabled(1)}>Toggle Tab 2 Enable</button>
      <TabComponent ref={tabRef}>
        <TabItemsDirective>
          <TabItemDirective header={{ text: 'Tab 1' }} content="Content 1" />
          <TabItemDirective header={{ text: 'Tab 2' }} content="Content 2" />
          <TabItemDirective header={{ text: 'Tab 3' }} content="Content 3" />
        </TabItemsDirective>
      </TabComponent>
    </div>
  );
}

hideTab(index, value)

hideTab(index, value)

Shows or hides a tab item at the specified index. Hidden tabs are removed from the DOM.
Parameters:
  • index
    - Index of the tab to show/hide
  • value
    (optional) - Boolean.
    true
    to hide,
    false
    to show. Default is
    true
Returns:
void
Example:
jsx
import React, { useRef, useState } from 'react';
import { TabComponent, TabItemsDirective, TabItemDirective } from '@syncfusion/ej2-react-navigations';

export default function HideTabExample() {
  const tabRef = useRef(null);
  const [visibleTabs, setVisibleTabs] = useState([true, true, true]);

  const toggleTabVisibility = (index) => {
    const newVisibleTabs = [...visibleTabs];
    newVisibleTabs[index] = !newVisibleTabs[index];
    setVisibleTabs(newVisibleTabs);
    tabRef.current.hideTab(index, !newVisibleTabs[index]);
  };

  return (
    <div>
      <div>
        <button onClick={() => toggleTabVisibility(0)}>
          Toggle Tab 1 Visibility
        </button>
        <button onClick={() => toggleTabVisibility(1)}>
          Toggle Tab 2 Visibility
        </button>
      </div>
      <TabComponent ref={tabRef}>
        <TabItemsDirective>
          <TabItemDirective header={{ text: 'Tab 1' }} content="Content 1" />
          <TabItemDirective header={{ text: 'Tab 2' }} content="Content 2" />
          <TabItemDirective header={{ text: 'Tab 3' }} content="Content 3" />
        </TabItemsDirective>
      </TabComponent>
    </div>
  );
}
显示或隐藏指定索引的选项卡项,隐藏的选项卡会从DOM中移除。
参数:
  • index
    - 要显示/隐藏的选项卡索引
  • value
    (可选)- 布尔值,
    true
    表示隐藏,
    false
    表示显示,默认值为
    true
返回值:
void
示例:
jsx
import React, { useRef, useState } from 'react';
import { TabComponent, TabItemsDirective, TabItemDirective } from '@syncfusion/ej2-react-navigations';

export default function HideTabExample() {
  const tabRef = useRef(null);
  const [visibleTabs, setVisibleTabs] = useState([true, true, true]);

  const toggleTabVisibility = (index) => {
    const newVisibleTabs = [...visibleTabs];
    newVisibleTabs[index] = !newVisibleTabs[index];
    setVisibleTabs(newVisibleTabs);
    tabRef.current.hideTab(index, !newVisibleTabs[index]);
  };

  return (
    <div>
      <div>
        <button onClick={() => toggleTabVisibility(0)}>
          Toggle Tab 1 Visibility
        </button>
        <button onClick={() => toggleTabVisibility(1)}>
          Toggle Tab 2 Visibility
        </button>
      </div>
      <TabComponent ref={tabRef}>
        <TabItemsDirective>
          <TabItemDirective header={{ text: 'Tab 1' }} content="Content 1" />
          <TabItemDirective header={{ text: 'Tab 2' }} content="Content 2" />
          <TabItemDirective header={{ text: 'Tab 3' }} content="Content 3" />
        </TabItemsDirective>
      </TabComponent>
    </div>
  );
}

getItemIndex(tabItemId)

getItemIndex(tabItemId)

Gets the index of a tab item by its ID.
Parameters:
  • tabItemId
    - The ID of the tab item
Returns:
number
- The index of the tab, or -1 if not found
Example:
jsx
import React, { useRef } from 'react';
import { TabComponent, TabItemsDirective, TabItemDirective } from '@syncfusion/ej2-react-navigations';

export default function GetItemIndexExample() {
  const tabRef = useRef(null);

  const findTabIndex = () => {
    const itemId = 'tab_2';
    const index = tabRef.current.getItemIndex(itemId);
    console.log(`Tab with ID '${itemId}' is at index: ${index}`);
  };

  return (
    <div>
      <button onClick={findTabIndex}>Find Tab Index</button>
      <TabComponent ref={tabRef}>
        <TabItemsDirective>
          <TabItemDirective id="tab_1" header={{ text: 'Tab 1' }} content="Content 1" />
          <TabItemDirective id="tab_2" header={{ text: 'Tab 2' }} content="Content 2" />
          <TabItemDirective id="tab_3" header={{ text: 'Tab 3' }} content="Content 3" />
        </TabItemsDirective>
      </TabComponent>
    </div>
  );
}
通过选项卡项的ID获取其索引。
参数:
  • tabItemId
    - 选项卡项的ID
返回值:
number
- 选项卡的索引,未找到则返回-1
示例:
jsx
import React, { useRef } from 'react';
import { TabComponent, TabItemsDirective, TabItemDirective } from '@syncfusion/ej2-react-navigations';

export default function GetItemIndexExample() {
  const tabRef = useRef(null);

  const findTabIndex = () => {
    const itemId = 'tab_2';
    const index = tabRef.current.getItemIndex(itemId);
    console.log(`Tab with ID '${itemId}' is at index: ${index}`);
  };

  return (
    <div>
      <button onClick={findTabIndex}>Find Tab Index</button>
      <TabComponent ref={tabRef}>
        <TabItemsDirective>
          <TabItemDirective id="tab_1" header={{ text: 'Tab 1' }} content="Content 1" />
          <TabItemDirective id="tab_2" header={{ text: 'Tab 2' }} content="Content 2" />
          <TabItemDirective id="tab_3" header={{ text: 'Tab 3' }} content="Content 3" />
        </TabItemsDirective>
      </TabComponent>
    </div>
  );
}

refresh()

refresh()

Refreshes the entire Tab component. Useful after dynamically changing items or properties.
Parameters: None
Returns:
void
Example:
jsx
import React, { useRef } from 'react';
import { TabComponent, TabItemsDirective, TabItemDirective } from '@syncfusion/ej2-react-navigations';

export default function RefreshTabExample() {
  const tabRef = useRef(null);

  const handleRefresh = () => {
    tabRef.current.refresh();
    console.log('Tab component refreshed');
  };

  return (
    <div>
      <button onClick={handleRefresh}>Refresh Tab</button>
      <TabComponent ref={tabRef}>
        <TabItemsDirective>
          <TabItemDirective header={{ text: 'Tab 1' }} content="Content 1" />
          <TabItemDirective header={{ text: 'Tab 2' }} content="Content 2" />
        </TabItemsDirective>
      </TabComponent>
    </div>
  );
}
刷新整个Tab组件,在动态修改选项卡项或属性后使用。
参数:
返回值:
void
示例:
jsx
import React, { useRef } from 'react';
import { TabComponent, TabItemsDirective, TabItemDirective } from '@syncfusion/ej2-react-navigations';

export default function RefreshTabExample() {
  const tabRef = useRef(null);

  const handleRefresh = () => {
    tabRef.current.refresh();
    console.log('Tab component refreshed');
  };

  return (
    <div>
      <button onClick={handleRefresh}>Refresh Tab</button>
      <TabComponent ref={tabRef}>
        <TabItemsDirective>
          <TabItemDirective header={{ text: 'Tab 1' }} content="Content 1" />
          <TabItemDirective header={{ text: 'Tab 2' }} content="Content 2" />
        </TabItemsDirective>
      </TabComponent>
    </div>
  );
}

refreshActiveTab()

refreshActiveTab()

Refreshes only the content of the currently active tab. Does not reload other tabs.
Parameters: None
Returns:
void
Example:
jsx
import React, { useRef } from 'react';
import { TabComponent, TabItemsDirective, TabItemDirective } from '@syncfusion/ej2-react-navigations';

export default function RefreshActiveTabExample() {
  const tabRef = useRef(null);

  const handleRefreshActive = () => {
    tabRef.current.refreshActiveTab();
    console.log('Active tab content refreshed');
  };

  return (
    <div>
      <button onClick={handleRefreshActive}>Refresh Active Tab</button>
      <TabComponent ref={tabRef}>
        <TabItemsDirective>
          <TabItemDirective header={{ text: 'Tab 1' }} content="Content 1" />
          <TabItemDirective header={{ text: 'Tab 2' }} content="Dynamically updated content" />
        </TabItemsDirective>
      </TabComponent>
    </div>
  );
}
仅刷新当前激活选项卡的内容,不会重新加载其他选项卡。
参数:
返回值:
void
示例:
jsx
import React, { useRef } from 'react';
import { TabComponent, TabItemsDirective, TabItemDirective } from '@syncfusion/ej2-react-navigations';

export default function RefreshActiveTabExample() {
  const tabRef = useRef(null);

  const handleRefreshActive = () => {
    tabRef.current.refreshActiveTab();
    console.log('Active tab content refreshed');
  };

  return (
    <div>
      <button onClick={handleRefreshActive}>Refresh Active Tab</button>
      <TabComponent ref={tabRef}>
        <TabItemsDirective>
          <TabItemDirective header={{ text: 'Tab 1' }} content="Content 1" />
          <TabItemDirective header={{ text: 'Tab 2' }} content="Dynamically updated content" />
        </TabItemsDirective>
      </TabComponent>
    </div>
  );
}

refreshActiveTabBorder()

refreshActiveTabBorder()

Refreshes the active tab's visual indicator (underline/border). Useful after styling changes.
Parameters: None
Returns:
void
Example:
jsx
import React, { useRef } from 'react';
import { TabComponent, TabItemsDirective, TabItemDirective } from '@syncfusion/ej2-react-navigations';

export default function RefreshBorderExample() {
  const tabRef = useRef(null);

  const handleRefreshBorder = () => {
    tabRef.current.refreshActiveTabBorder();
  };

  return (
    <div>
      <button onClick={handleRefreshBorder}>Refresh Border</button>
      <TabComponent ref={tabRef}>
        <TabItemsDirective>
          <TabItemDirective header={{ text: 'Tab 1' }} content="Content 1" />
          <TabItemDirective header={{ text: 'Tab 2' }} content="Content 2" />
        </TabItemsDirective>
      </TabComponent>
    </div>
  );
}
刷新激活选项卡的视觉指示器(下划线/边框),在样式修改后使用。
参数:
返回值:
void
示例:
jsx
import React, { useRef } from 'react';
import { TabComponent, TabItemsDirective, TabItemDirective } from '@syncfusion/ej2-react-navigations';

export default function RefreshBorderExample() {
  const tabRef = useRef(null);

  const handleRefreshBorder = () => {
    tabRef.current.refreshActiveTabBorder();
  };

  return (
    <div>
      <button onClick={handleRefreshBorder}>Refresh Border</button>
      <TabComponent ref={tabRef}>
        <TabItemsDirective>
          <TabItemDirective header={{ text: 'Tab 1' }} content="Content 1" />
          <TabItemDirective header={{ text: 'Tab 2' }} content="Content 2" />
        </TabItemsDirective>
      </TabComponent>
    </div>
  );
}

refreshOverflow()

refreshOverflow()

Reorganizes and adjusts the Tab headers to fit the available width without re-rendering the entire component. Useful for responsive layouts.
Parameters: None
Returns:
void
Example:
jsx
import React, { useRef, useState } from 'react';
import { TabComponent, TabItemsDirective, TabItemDirective } from '@syncfusion/ej2-react-navigations';

export default function RefreshOverflowExample() {
  const tabRef = useRef(null);
  const [tabCount, setTabCount] = useState(3);

  const handleWindowResize = () => {
    if (tabRef.current) {
      tabRef.current.refreshOverflow();
    }
  };

  React.useEffect(() => {
    window.addEventListener('resize', handleWindowResize);
    return () => window.removeEventListener('resize', handleWindowResize);
  }, []);

  const addMoreTabs = () => {
    const newTab = {
      header: { text: `Tab ${tabCount + 1}` },
      content: `Content ${tabCount + 1}`
    };
    tabRef.current.addTab([newTab]);
    setTabCount(tabCount + 1);
    tabRef.current.refreshOverflow();
  };

  return (
    <div>
      <button onClick={addMoreTabs}>Add Tab & Refresh Overflow</button>
      <TabComponent ref={tabRef} width="100%">
        <TabItemsDirective>
          <TabItemDirective header={{ text: 'Tab 1' }} content="Content 1" />
          <TabItemDirective header={{ text: 'Tab 2' }} content="Content 2" />
          <TabItemDirective header={{ text: 'Tab 3' }} content="Content 3" />
        </TabItemsDirective>
      </TabComponent>
    </div>
  );
}
重新组织并调整选项卡标题以适应可用宽度,无需重新渲染整个组件,适用于响应式布局。
参数:
返回值:
void
示例:
jsx
import React, { useRef, useState } from 'react';
import { TabComponent, TabItemsDirective, TabItemDirective } from '@syncfusion/ej2-react-navigations';

export default function RefreshOverflowExample() {
  const tabRef = useRef(null);
  const [tabCount, setTabCount] = useState(3);

  const handleWindowResize = () => {
    if (tabRef.current) {
      tabRef.current.refreshOverflow();
    }
  };

  React.useEffect(() => {
    window.addEventListener('resize', handleWindowResize);
    return () => window.removeEventListener('resize', handleWindowResize);
  }, []);

  const addMoreTabs = () => {
    const newTab = {
      header: { text: `Tab ${tabCount + 1}` },
      content: `Content ${tabCount + 1}`
    };
    tabRef.current.addTab([newTab]);
    setTabCount(tabCount + 1);
    tabRef.current.refreshOverflow();
  };

  return (
    <div>
      <button onClick={addMoreTabs}>Add Tab & Refresh Overflow</button>
      <TabComponent ref={tabRef} width="100%">
        <TabItemsDirective>
          <TabItemDirective header={{ text: 'Tab 1' }} content="Content 1" />
          <TabItemDirective header={{ text: 'Tab 2' }} content="Content 2" />
          <TabItemDirective header={{ text: 'Tab 3' }} content="Content 3" />
        </TabItemsDirective>
      </TabComponent>
    </div>
  );
}

disable(value)

disable(value)

Disables or enables the entire Tab component.
Parameters:
  • value
    - Boolean.
    true
    to disable,
    false
    to enable
Returns:
void
Example:
jsx
import React, { useRef, useState } from 'react';
import { TabComponent, TabItemsDirective, TabItemDirective } from '@syncfusion/ej2-react-navigations';

export default function DisableTabExample() {
  const tabRef = useRef(null);
  const [isDisabled, setIsDisabled] = useState(false);

  const toggleDisable = () => {
    tabRef.current.disable(!isDisabled);
    setIsDisabled(!isDisabled);
  };

  return (
    <div>
      <button onClick={toggleDisable}>
        {isDisabled ? 'Enable' : 'Disable'} Tab Component
      </button>
      <TabComponent ref={tabRef}>
        <TabItemsDirective>
          <TabItemDirective header={{ text: 'Tab 1' }} content="Content 1" />
          <TabItemDirective header={{ text: 'Tab 2' }} content="Content 2" />
        </TabItemsDirective>
      </TabComponent>
    </div>
  );
}
禁用或启用整个Tab组件。
参数:
  • value
    - 布尔值,
    true
    表示禁用,
    false
    表示启用
返回值:
void
示例:
jsx
import React, { useRef, useState } from 'react';
import { TabComponent, TabItemsDirective, TabItemDirective } from '@syncfusion/ej2-react-navigations';

export default function DisableTabExample() {
  const tabRef = useRef(null);
  const [isDisabled, setIsDisabled] = useState(false);

  const toggleDisable = () => {
    tabRef.current.disable(!isDisabled);
    setIsDisabled(!isDisabled);
  };

  return (
    <div>
      <button onClick={toggleDisable}>
        {isDisabled ? 'Enable' : 'Disable'} Tab Component
      </button>
      <TabComponent ref={tabRef}>
        <TabItemsDirective>
          <TabItemDirective header={{ text: 'Tab 1' }} content="Content 1" />
          <TabItemDirective header={{ text: 'Tab 2' }} content="Content 2" />
        </TabItemsDirective>
      </TabComponent>
    </div>
  );
}

destroy()

destroy()

Removes the component from the DOM and detaches all event handlers, attributes, and classes.
Parameters: None
Returns:
void
Example:
jsx
import React, { useRef } from 'react';
import { TabComponent, TabItemsDirective, TabItemDirective } from '@syncfusion/ej2-react-navigations';

export default function DestroyTabExample() {
  const tabRef = useRef(null);

  const handleDestroy = () => {
    tabRef.current.destroy();
    console.log('Tab component destroyed');
  };

  return (
    <div>
      <button onClick={handleDestroy}>Destroy Tab</button>
      <TabComponent ref={tabRef}>
        <TabItemsDirective>
          <TabItemDirective header={{ text: 'Tab 1' }} content="Content 1" />
          <TabItemDirective header={{ text: 'Tab 2' }} content="Content 2" />
        </TabItemsDirective>
      </TabComponent>
    </div>
  );
}
将组件从DOM中移除,并解绑所有事件处理器、属性和类。
参数:
返回值:
void
示例:
jsx
import React, { useRef } from 'react';
import { TabComponent, TabItemsDirective, TabItemDirective } from '@syncfusion/ej2-react-navigations';

export default function DestroyTabExample() {
  const tabRef = useRef(null);

  const handleDestroy = () => {
    tabRef.current.destroy();
    console.log('Tab component destroyed');
  };

  return (
    <div>
      <button onClick={handleDestroy}>Destroy Tab</button>
      <TabComponent ref={tabRef}>
        <TabItemsDirective>
          <TabItemDirective header={{ text: 'Tab 1' }} content="Content 1" />
          <TabItemDirective header={{ text: 'Tab 2' }} content="Content 2" />
        </TabItemsDirective>
      </TabComponent>
    </div>
  );
}

Events & Event Arguments

事件与事件参数

The Tab component provides comprehensive event support for handling user interactions and component state changes.
Tab组件提供全面的事件支持,用于处理用户交互和组件状态变化。

selected

selected

Fired after a tab item is selected. Used to execute actions when the user switches to a different tab.
Event Arguments:
SelectEventArgs
SelectEventArgs Properties:
  • selectedIndex
    (number) - Index of the newly selected tab
  • selectedItem
    (HTMLElement) - DOM element of the selected tab
  • selectedContent
    (HTMLElement) - Content area of the selected tab
  • previousIndex
    (number) - Index of the previously selected tab
  • previousItem
    (HTMLElement) - DOM element of the previous tab
  • isInteracted
    (boolean) - Whether selection was triggered by user interaction (true) or programmatically (false)
  • isSwiped
    (boolean) - Whether selection was triggered by swipe gesture
  • preventFocus
    (boolean) - Set to true to prevent focus on selected tab
  • cancel
    (boolean) - Set to true to prevent the selection
Example:
jsx
import React, { useRef, useState } from 'react';
import { TabComponent, TabItemsDirective, TabItemDirective } from '@syncfusion/ej2-react-navigations';

export default function SelectedEventExample() {
  const tabRef = useRef(null);
  const [selectedIndex, setSelectedIndex] = useState(0);

  const handleTabSelected = (args) => {
    console.log('Tab selected:', {
      selectedIndex: args.selectedIndex,
      previousIndex: args.previousIndex,
      isInteracted: args.isInteracted,
      isSwiped: args.isSwiped
    });
    setSelectedIndex(args.selectedIndex);
  };

  return (
    <div>
      <p>Currently selected tab index: {selectedIndex}</p>
      <TabComponent ref={tabRef} selected={handleTabSelected}>
        <TabItemsDirective>
          <TabItemDirective header={{ text: 'Tab 1' }} content="Content 1" />
          <TabItemDirective header={{ text: 'Tab 2' }} content="Content 2" />
          <TabItemDirective header={{ text: 'Tab 3' }} content="Content 3" />
        </TabItemsDirective>
      </TabComponent>
    </div>
  );
}
选项卡项被选中后触发,用于在用户切换到不同选项卡时执行操作。
事件参数:
SelectEventArgs
SelectEventArgs属性:
  • selectedIndex
    (number) - 新选中选项卡的索引
  • selectedItem
    (HTMLElement) - 选中选项卡的DOM元素
  • selectedContent
    (HTMLElement) - 选中选项卡的内容区域
  • previousIndex
    (number) - 之前选中选项卡的索引
  • previousItem
    (HTMLElement) - 之前选中选项卡的DOM元素
  • isInteracted
    (boolean) - 选择操作是否由用户交互触发(true)或编程触发(false)
  • isSwiped
    (boolean) - 选择操作是否由滑动手势触发
  • preventFocus
    (boolean) - 设置为true可阻止选中选项卡获得焦点
  • cancel
    (boolean) - 设置为true可阻止选择操作
示例:
jsx
import React, { useRef, useState } from 'react';
import { TabComponent, TabItemsDirective, TabItemDirective } from '@syncfusion/ej2-react-navigations';

export default function SelectedEventExample() {
  const tabRef = useRef(null);
  const [selectedIndex, setSelectedIndex] = useState(0);

  const handleTabSelected = (args) => {
    console.log('Tab selected:', {
      selectedIndex: args.selectedIndex,
      previousIndex: args.previousIndex,
      isInteracted: args.isInteracted,
      isSwiped: args.isSwiped
    });
    setSelectedIndex(args.selectedIndex);
  };

  return (
    <div>
      <p>Currently selected tab index: {selectedIndex}</p>
      <TabComponent ref={tabRef} selected={handleTabSelected}>
        <TabItemsDirective>
          <TabItemDirective header={{ text: 'Tab 1' }} content="Content 1" />
          <TabItemDirective header={{ text: 'Tab 2' }} content="Content 2" />
          <TabItemDirective header={{ text: 'Tab 3' }} content="Content 3" />
        </TabItemsDirective>
      </TabComponent>
    </div>
  );
}

selecting

selecting

Fired before a tab item is selected. Use this to prevent selection under certain conditions.
Event Arguments:
SelectingEventArgs
(same properties as
SelectEventArgs
)
Example:
jsx
import React, { useRef } from 'react';
import { TabComponent, TabItemsDirective, TabItemDirective } from '@syncfusion/ej2-react-navigations';

export default function SelectingEventExample() {
  const handleTabSelecting = (args) => {
    // Prevent selection of tab at index 1
    if (args.selectedIndex === 1) {
      console.log('Tab 2 selection prevented');
      args.cancel = true;
    }
  };

  return (
    <TabComponent selecting={handleTabSelecting}>
      <TabItemsDirective>
        <TabItemDirective header={{ text: 'Tab 1' }} content="Content 1" />
        <TabItemDirective header={{ text: 'Tab 2 (Locked)' }} content="Content 2" />
        <TabItemDirective header={{ text: 'Tab 3' }} content="Content 3" />
      </TabItemsDirective>
    </TabComponent>
  );
}
选项卡项被选中前触发,用于在特定条件下阻止选择操作。
事件参数:
SelectingEventArgs
(属性与
SelectEventArgs
相同)
示例:
jsx
import React, { useRef } from 'react';
import { TabComponent, TabItemsDirective, TabItemDirective } from '@syncfusion/ej2-react-navigations';

export default function SelectingEventExample() {
  const handleTabSelecting = (args) => {
    // 阻止选择索引为1的选项卡
    if (args.selectedIndex === 1) {
      console.log('Tab 2 selection prevented');
      args.cancel = true;
    }
  };

  return (
    <TabComponent selecting={handleTabSelecting}>
      <TabItemsDirective>
        <TabItemDirective header={{ text: 'Tab 1' }} content="Content 1" />
        <TabItemDirective header={{ text: 'Tab 2 (Locked)' }} content="Content 2" />
        <TabItemDirective header={{ text: 'Tab 3' }} content="Content 3" />
      </TabItemsDirective>
    </TabComponent>
  );
}

added

added

Fired after a new tab item is added to the component.
Event Arguments:
AddEventArgs
AddEventArgs Properties:
  • addedItems
    (TabItemModel[]) - Array of added tab items
  • name
    (string) - Name of the event
  • cancel
    (boolean) - Set to true to prevent the action
Example:
jsx
import React, { useRef } from 'react';
import { TabComponent, TabItemsDirective, TabItemDirective } from '@syncfusion/ej2-react-navigations';

export default function AddedEventExample() {
  const tabRef = useRef(null);

  const handleTabAdded = (args) => {
    console.log('Tabs added:', args.addedItems.length);
    console.log('First added item header:', args.addedItems[0].header.text);
  };

  const handleAddTab = () => {
    const newItems = [
      {
        header: { text: 'Newly Added Tab' },
        content: 'This tab was added dynamically'
      }
    ];
    tabRef.current.addTab(newItems);
  };

  return (
    <div>
      <button onClick={handleAddTab}>Add Tab</button>
      <TabComponent ref={tabRef} added={handleTabAdded}>
        <TabItemsDirective>
          <TabItemDirective header={{ text: 'Tab 1' }} content="Content 1" />
          <TabItemDirective header={{ text: 'Tab 2' }} content="Content 2" />
        </TabItemsDirective>
      </TabComponent>
    </div>
  );
}
新选项卡项添加到组件后触发。
事件参数:
AddEventArgs
AddEventArgs属性:
  • addedItems
    (TabItemModel[]) - 添加的选项卡项数组
  • name
    (string) - 事件名称
  • cancel
    (boolean) - 设置为true可阻止操作
示例:
jsx
import React, { useRef } from 'react';
import { TabComponent, TabItemsDirective, TabItemDirective } from '@syncfusion/ej2-react-navigations';

export default function AddedEventExample() {
  const tabRef = useRef(null);

  const handleTabAdded = (args) => {
    console.log('Tabs added:', args.addedItems.length);
    console.log('First added item header:', args.addedItems[0].header.text);
  };

  const handleAddTab = () => {
    const newItems = [
      {
        header: { text: 'Newly Added Tab' },
        content: 'This tab was added dynamically'
      }
    ];
    tabRef.current.addTab(newItems);
  };

  return (
    <div>
      <button onClick={handleAddTab}>Add Tab</button>
      <TabComponent ref={tabRef} added={handleTabAdded}>
        <TabItemsDirective>
          <TabItemDirective header={{ text: 'Tab 1' }} content="Content 1" />
          <TabItemDirective header={{ text: 'Tab 2' }} content="Content 2" />
        </TabItemsDirective>
      </TabComponent>
    </div>
  );
}

adding

adding

Fired before a new tab item is added. Use this to validate or modify items before addition.
Event Arguments:
AddEventArgs
Example:
jsx
import React, { useRef } from 'react';
import { TabComponent, TabItemsDirective, TabItemDirective } from '@syncfusion/ej2-react-navigations';

export default function AddingEventExample() {
  const tabRef = useRef(null);
  const maxTabs = 5;

  const handleTabAdding = (args) => {
    const totalTabs = tabRef.current.items.length + args.addedItems.length;
    if (totalTabs > maxTabs) {
      console.log(`Cannot exceed ${maxTabs} tabs`);
      args.cancel = true;
    }
  };

  const handleAddTab = () => {
    const newItems = [
      {
        header: { text: `Tab ${tabRef.current.items.length + 1}` },
        content: 'New content'
      }
    ];
    tabRef.current.addTab(newItems);
  };

  return (
    <div>
      <button onClick={handleAddTab}>Add Tab (Max 5)</button>
      <TabComponent ref={tabRef} adding={handleTabAdding}>
        <TabItemsDirective>
          <TabItemDirective header={{ text: 'Tab 1' }} content="Content 1" />
          <TabItemDirective header={{ text: 'Tab 2' }} content="Content 2" />
        </TabItemsDirective>
      </TabComponent>
    </div>
  );
}
新选项卡项添加前触发,用于在添加前验证或修改选项卡项。
事件参数:
AddEventArgs
示例:
jsx
import React, { useRef } from 'react';
import { TabComponent, TabItemsDirective, TabItemDirective } from '@syncfusion/ej2-react-navigations';

export default function AddingEventExample() {
  const tabRef = useRef(null);
  const maxTabs = 5;

  const handleTabAdding = (args) => {
    const totalTabs = tabRef.current.items.length + args.addedItems.length;
    if (totalTabs > maxTabs) {
      console.log(`Cannot exceed ${maxTabs} tabs`);
      args.cancel = true;
    }
  };

  const handleAddTab = () => {
    const newItems = [
      {
        header: { text: `Tab ${tabRef.current.items.length + 1}` },
        content: 'New content'
      }
    ];
    tabRef.current.addTab(newItems);
  };

  return (
    <div>
      <button onClick={handleAddTab}>Add Tab (Max 5)</button>
      <TabComponent ref={tabRef} adding={handleTabAdding}>
        <TabItemsDirective>
          <TabItemDirective header={{ text: 'Tab 1' }} content="Content 1" />
          <TabItemDirective header={{ text: 'Tab 2' }} content="Content 2" />
        </TabItemsDirective>
      </TabComponent>
    </div>
  );
}

removed

removed

Fired after a tab item is removed from the component.
Event Arguments:
RemoveEventArgs
RemoveEventArgs Properties:
  • removedItem
    (HTMLElement) - DOM element of the removed tab
  • index
    (number) - Index of the removed tab
  • name
    (string) - Name of the event
Example:
jsx
import React, { useRef, useState } from 'react';
import { TabComponent, TabItemsDirective, TabItemDirective } from '@syncfusion/ej2-react-navigations';

export default function RemovedEventExample() {
  const tabRef = useRef(null);
  const [removedCount, setRemovedCount] = useState(0);

  const handleTabRemoved = (args) => {
    console.log(`Tab at index ${args.index} was removed`);
    setRemovedCount(removedCount + 1);
  };

  const handleRemoveTab = (index) => {
    tabRef.current.removeTab(index);
  };

  return (
    <div>
      <p>Tabs removed: {removedCount}</p>
      <button onClick={() => handleRemoveTab(0)}>Remove First Tab</button>
      <TabComponent ref={tabRef} removed={handleTabRemoved}>
        <TabItemsDirective>
          <TabItemDirective header={{ text: 'Tab 1' }} content="Content 1" />
          <TabItemDirective header={{ text: 'Tab 2' }} content="Content 2" />
          <TabItemDirective header={{ text: 'Tab 3' }} content="Content 3" />
        </TabItemsDirective>
      </TabComponent>
    </div>
  );
}
选项卡项从组件中移除后触发。
事件参数:
RemoveEventArgs
RemoveEventArgs属性:
  • removedItem
    (HTMLElement) - 被移除选项卡的DOM元素
  • index
    (number) - 被移除选项卡的索引
  • name
    (string) - 事件名称
示例:
jsx
import React, { useRef, useState } from 'react';
import { TabComponent, TabItemsDirective, TabItemDirective } from '@syncfusion/ej2-react-navigations';

export default function RemovedEventExample() {
  const tabRef = useRef(null);
  const [removedCount, setRemovedCount] = useState(0);

  const handleTabRemoved = (args) => {
    console.log(`Tab at index ${args.index} was removed`);
    setRemovedCount(removedCount + 1);
  };

  const handleRemoveTab = (index) => {
    tabRef.current.removeTab(index);
  };

  return (
    <div>
      <p>Tabs removed: {removedCount}</p>
      <button onClick={() => handleRemoveTab(0)}>Remove First Tab</button>
      <TabComponent ref={tabRef} removed={handleTabRemoved}>
        <TabItemsDirective>
          <TabItemDirective header={{ text: 'Tab 1' }} content="Content 1" />
          <TabItemDirective header={{ text: 'Tab 2' }} content="Content 2" />
          <TabItemDirective header={{ text: 'Tab 3' }} content="Content 3" />
        </TabItemsDirective>
      </TabComponent>
    </div>
  );
}

removing

removing

Fired before a tab item is removed. Use this to prevent removal under certain conditions.
Event Arguments:
RemoveEventArgs
Example:
jsx
import React, { useRef } from 'react';
import { TabComponent, TabItemsDirective, TabItemDirective } from '@syncfusion/ej2-react-navigations';

export default function RemovingEventExample() {
  const handleTabRemoving = (args) => {
    const confirmed = window.confirm('Are you sure you want to remove this tab?');
    if (!confirmed) {
      args.cancel = true;
    }
  };

  return (
    <TabComponent removing={handleTabRemoving} showCloseButton={true}>
      <TabItemsDirective>
        <TabItemDirective header={{ text: 'Tab 1' }} content="Content 1" />
        <TabItemDirective header={{ text: 'Tab 2' }} content="Content 2" />
        <TabItemDirective header={{ text: 'Tab 3' }} content="Content 3" />
      </TabItemsDirective>
    </TabComponent>
  );
}
选项卡项被移除前触发,用于在特定条件下阻止移除操作。
事件参数:
RemoveEventArgs
示例:
jsx
import React, { useRef } from 'react';
import { TabComponent, TabItemsDirective, TabItemDirective } from '@syncfusion/ej2-react-navigations';

export default function RemovingEventExample() {
  const handleTabRemoving = (args) => {
    const confirmed = window.confirm('Are you sure you want to remove this tab?');
    if (!confirmed) {
      args.cancel = true;
    }
  };

  return (
    <TabComponent removing={handleTabRemoving} showCloseButton={true}>
      <TabItemsDirective>
        <TabItemDirective header={{ text: 'Tab 1' }} content="Content 1" />
        <TabItemDirective header={{ text: 'Tab 2' }} content="Content 2" />
        <TabItemDirective header={{ text: 'Tab 3' }} content="Content 3" />
      </TabItemsDirective>
    </TabComponent>
  );
}

onDragStart

onDragStart

Fired before dragging a tab item. Use this to prevent dragging specific tabs or customize drag behavior.
Event Arguments:
DragEventArgs
DragEventArgs Properties:
  • draggedItem
    (HTMLElement) - The tab being dragged
  • clonedElement
    (HTMLElement) - Clone of the dragged element
  • event
    (MouseEvent) - The drag event
  • index
    (number) - Index of the dragged tab
  • cancel
    (boolean) - Set to true to prevent dragging
  • name
    (string) - Name of the event
  • target
    (HTMLElement) - Target element
  • droppedItem
    (HTMLElement) - The item being dropped on
Example:
jsx
import React, { useRef } from 'react';
import { TabComponent, TabItemsDirective, TabItemDirective } from '@syncfusion/ej2-react-navigations';

export default function OnDragStartExample() {
  const handleDragStart = (args) => {
    // Prevent dragging the first tab (index 0)
    if (args.index === 0) {
      args.cancel = true;
      console.log('First tab cannot be dragged');
    }
  };

  return (
    <TabComponent allowDragAndDrop={true} onDragStart={handleDragStart}>
      <TabItemsDirective>
        <TabItemDirective header={{ text: 'Tab 1 (Locked)' }} content="Content 1" />
        <TabItemDirective header={{ text: 'Tab 2' }} content="Content 2" />
        <TabItemDirective header={{ text: 'Tab 3' }} content="Content 3" />
      </TabItemsDirective>
    </TabComponent>
  );
}
选项卡项开始拖动前触发,用于阻止特定选项卡的拖动或自定义拖动行为。
事件参数:
DragEventArgs
DragEventArgs属性:
  • draggedItem
    (HTMLElement) - 正在拖动的选项卡
  • clonedElement
    (HTMLElement) - 拖动元素的克隆体
  • event
    (MouseEvent) - 拖动事件
  • index
    (number) - 被拖动选项卡的索引
  • cancel
    (boolean) - 设置为true可阻止拖动操作
  • name
    (string) - 事件名称
  • target
    (HTMLElement) - 目标元素
  • droppedItem
    (HTMLElement) - 被拖放的目标选项卡
示例:
jsx
import React, { useRef } from 'react';
import { TabComponent, TabItemsDirective, TabItemDirective } from '@syncfusion/ej2-react-navigations';

export default function OnDragStartExample() {
  const handleDragStart = (args) => {
    // 阻止拖动第一个选项卡(索引0)
    if (args.index === 0) {
      args.cancel = true;
      console.log('First tab cannot be dragged');
    }
  };

  return (
    <TabComponent allowDragAndDrop={true} onDragStart={handleDragStart}>
      <TabItemsDirective>
        <TabItemDirective header={{ text: 'Tab 1 (Locked)' }} content="Content 1" />
        <TabItemDirective header={{ text: 'Tab 2' }} content="Content 2" />
        <TabItemDirective header={{ text: 'Tab 3' }} content="Content 3" />
      </TabItemsDirective>
    </TabComponent>
  );
}

dragging

dragging

Fired while a tab is being dragged.
Event Arguments:
DragEventArgs
Example:
jsx
import React, { useRef, useState } from 'react';
import { TabComponent, TabItemsDirective, TabItemDirective } from '@syncfusion/ej2-react-navigations';

export default function DraggingEventExample() {
  const [dragStatus, setDragStatus] = useState('');

  const handleDragging = (args) => {
    setDragStatus(`Dragging tab at index ${args.index}`);
  };

  return (
    <div>
      <p>Drag status: {dragStatus}</p>
      <TabComponent allowDragAndDrop={true} dragging={handleDragging}>
        <TabItemsDirective>
          <TabItemDirective header={{ text: 'Tab 1' }} content="Content 1" />
          <TabItemDirective header={{ text: 'Tab 2' }} content="Content 2" />
          <TabItemDirective header={{ text: 'Tab 3' }} content="Content 3" />
        </TabItemsDirective>
      </TabComponent>
    </div>
  );
}
选项卡拖动过程中触发。
事件参数:
DragEventArgs
示例:
jsx
import React, { useRef, useState } from 'react';
import { TabComponent, TabItemsDirective, TabItemDirective } from '@syncfusion/ej2-react-navigations';

export default function DraggingEventExample() {
  const [dragStatus, setDragStatus] = useState('');

  const handleDragging = (args) => {
    setDragStatus(`Dragging tab at index ${args.index}`);
  };

  return (
    <div>
      <p>Drag status: {dragStatus}</p>
      <TabComponent allowDragAndDrop={true} dragging={handleDragging}>
        <TabItemsDirective>
          <TabItemDirective header={{ text: 'Tab 1' }} content="Content 1" />
          <TabItemDirective header={{ text: 'Tab 2' }} content="Content 2" />
          <TabItemDirective header={{ text: 'Tab 3' }} content="Content 3" />
        </TabItemsDirective>
      </TabComponent>
    </div>
  );
}

dragged

dragged

Fired after a tab has been successfully dropped to a new position.
Event Arguments:
DragEventArgs
Example:
jsx
import React, { useRef, useState } from 'react';
import { TabComponent, TabItemsDirective, TabItemDirective } from '@syncfusion/ej2-react-navigations';

export default function DraggedEventExample() {
  const [dropMessage, setDropMessage] = useState('');

  const handleDragged = (args) => {
    setDropMessage(`Tab dropped at new position. Index: ${args.index}`);
    console.log('Tab reordered successfully');
  };

  return (
    <div>
      <p>{dropMessage}</p>
      <TabComponent allowDragAndDrop={true} dragged={handleDragged}>
        <TabItemsDirective>
          <TabItemDirective header={{ text: 'Tab 1' }} content="Content 1" />
          <TabItemDirective header={{ text: 'Tab 2' }} content="Content 2" />
          <TabItemDirective header={{ text: 'Tab 3' }} content="Content 3" />
        </TabItemsDirective>
      </TabComponent>
    </div>
  );
}
选项卡成功拖放到新位置后触发。
事件参数:
DragEventArgs
示例:
jsx
import React, { useRef, useState } from 'react';
import { TabComponent, TabItemsDirective, TabItemDirective } from '@syncfusion/ej2-react-navigations';

export default function DraggedEventExample() {
  const [dropMessage, setDropMessage] = useState('');

  const handleDragged = (args) => {
    setDropMessage(`Tab dropped at new position. Index: ${args.index}`);
    console.log('Tab reordered successfully');
  };

  return (
    <div>
      <p>{dropMessage}</p>
      <TabComponent allowDragAndDrop={true} dragged={handleDragged}>
        <TabItemsDirective>
          <TabItemDirective header={{ text: 'Tab 1' }} content="Content 1" />
          <TabItemDirective header={{ text: 'Tab 2' }} content="Content 2" />
          <TabItemDirective header={{ text: 'Tab 3' }} content="Content 3" />
        </TabItemsDirective>
      </TabComponent>
    </div>
  );
}

created

created

Fired after the Tab component is completely rendered and initialized.
Event Arguments:
Event
Example:
jsx
import React, { useRef } from 'react';
import { TabComponent, TabItemsDirective, TabItemDirective } from '@syncfusion/ej2-react-navigations';

export default function CreatedEventExample() {
  const tabRef = useRef(null);

  const handleCreated = () => {
    console.log('Tab component created and initialized');
    console.log('Total tabs:', tabRef.current.items.length);
  };

  return (
    <TabComponent ref={tabRef} created={handleCreated}>
      <TabItemsDirective>
        <TabItemDirective header={{ text: 'Tab 1' }} content="Content 1" />
        <TabItemDirective header={{ text: 'Tab 2' }} content="Content 2" />
      </TabItemsDirective>
    </TabComponent>
  );
}
Tab组件完全渲染并初始化后触发。
事件参数:
Event
示例:
jsx
import React, { useRef } from 'react';
import { TabComponent, TabItemsDirective, TabItemDirective } from '@syncfusion/ej2-react-navigations';

export default function CreatedEventExample() {
  const tabRef = useRef(null);

  const handleCreated = () => {
    console.log('Tab component created and initialized');
    console.log('Total tabs:', tabRef.current.items.length);
  };

  return (
    <TabComponent ref={tabRef} created={handleCreated}>
      <TabItemsDirective>
        <TabItemDirective header={{ text: 'Tab 1' }} content="Content 1" />
        <TabItemDirective header={{ text: 'Tab 2' }} content="Content 2" />
      </TabItemsDirective>
    </TabComponent>
  );
}

destroyed

destroyed

Fired when the Tab component is destroyed and removed from the DOM.
Event Arguments:
Event
Example:
jsx
import React, { useRef, useState } from 'react';
import { TabComponent, TabItemsDirective, TabItemDirective } from '@syncfusion/ej2-react-navigations';

export default function DestroyedEventExample() {
  const [showTab, setShowTab] = useState(true);

  const handleDestroyed = () => {
    console.log('Tab component destroyed');
    alert('Tab component has been removed from DOM');
  };

  return (
    <div>
      <button onClick={() => setShowTab(!showTab)}>
        {showTab ? 'Destroy' : 'Create'} Tab
      </button>
      {showTab && (
        <TabComponent destroyed={handleDestroyed}>
          <TabItemsDirective>
            <TabItemDirective header={{ text: 'Tab 1' }} content="Content 1" />
            <TabItemDirective header={{ text: 'Tab 2' }} content="Content 2" />
          </TabItemsDirective>
        </TabComponent>
      )}
    </div>
  );
}
Tab组件被销毁并从DOM中移除时触发。
事件参数:
Event
示例:
jsx
import React, { useRef, useState } from 'react';
import { TabComponent, TabItemsDirective, TabItemDirective } from '@syncfusion/ej2-react-navigations';

export default function DestroyedEventExample() {
  const [showTab, setShowTab] = useState(true);

  const handleDestroyed = () => {
    console.log('Tab component destroyed');
    alert('Tab component has been removed from DOM');
  };

  return (
    <div>
      <button onClick={() => setShowTab(!showTab)}>
        {showTab ? 'Destroy' : 'Create'} Tab
      </button>
      {showTab && (
        <TabComponent destroyed={handleDestroyed}>
          <TabItemsDirective>
            <TabItemDirective header={{ text: 'Tab 1' }} content="Content 1" />
            <TabItemDirective header={{ text: 'Tab 2' }} content="Content 2" />
          </TabItemsDirective>
        </TabComponent>
      )}
    </div>
  );
}

Animation & Advanced Settings

动画与高级设置

The Tab component supports advanced features including animations, HTML sanitization, and state persistence.
Tab组件支持动画、HTML内容清理和状态持久化等高级功能。

Animation Configuration

动画配置

Control how tab content transitions between selections using the
animation
property.
Animation Settings:
  • previous
    - Animation effect when navigating to previous tab
  • next
    - Animation effect when navigating to next tab
  • Each animation has:
    effect
    ,
    duration
    (ms),
    easing
Available Animation Effects:
  • SlideLeftIn
    - Slide from right to left
  • SlideRightIn
    - Slide from left to right
  • SlideUpIn
    - Slide from bottom to top
  • SlideDownIn
    - Slide from top to bottom
  • FadeIn
    - Fade in effect
  • FadeOut
    - Fade out effect
  • FadeZoomIn
    - Fade with zoom in
  • FadeZoomOut
    - Fade with zoom out
  • ZoomIn
    - Zoom in effect
  • ZoomOut
    - Zoom out effect
  • None
    - No animation
Example: Custom Animation
jsx
import React, { useRef } from 'react';
import { TabComponent, TabItemsDirective, TabItemDirective } from '@syncfusion/ej2-react-navigations';

export default function AnimationExample() {
  const tabRef = useRef(null);

  const animationSettings = {
    previous: { effect: 'SlideLeftIn', duration: 600, easing: 'ease' },
    next: { effect: 'SlideRightIn', duration: 600, easing: 'ease' }
  };

  return (
    <TabComponent ref={tabRef} animation={animationSettings}>
      <TabItemsDirective>
        <TabItemDirective header={{ text: 'Twitter' }} content="Twitter is an online social networking service..." />
        <TabItemDirective header={{ text: 'Facebook' }} content="Facebook is an online social networking service..." />
        <TabItemDirective header={{ text: 'WhatsApp' }} content="WhatsApp Messenger is a proprietary cross-platform instant messaging client..." />
      </TabItemsDirective>
    </TabComponent>
  );
}
Example: Disabling Animation
jsx
import React from 'react';
import { TabComponent, TabItemsDirective, TabItemDirective } from '@syncfusion/ej2-react-navigations';

export default function NoAnimationExample() {
  const animationSettings = {
    previous: { effect: 'None' },
    next: { effect: 'None' }
  };

  return (
    <TabComponent animation={animationSettings}>
      <TabItemsDirective>
        <TabItemDirective header={{ text: 'Tab 1' }} content="Content 1" />
        <TabItemDirective header={{ text: 'Tab 2' }} content="Content 2" />
      </TabItemsDirective>
    </TabComponent>
  );
}
使用
animation
属性控制选项卡内容切换时的过渡效果。
动画设置:
  • previous
    - 切换到上一个选项卡时的动画效果
  • next
    - 切换到下一个选项卡时的动画效果
  • 每个动画包含:
    effect
    duration
    (毫秒)、
    easing
可用动画效果:
  • SlideLeftIn
    - 从右向左滑动
  • SlideRightIn
    - 从左向右滑动
  • SlideUpIn
    - 从下向上滑动
  • SlideDownIn
    - 从上向下滑动
  • FadeIn
    - 淡入效果
  • FadeOut
    - 淡出效果
  • FadeZoomIn
    - 淡入并放大
  • FadeZoomOut
    - 淡出并缩小
  • ZoomIn
    - 放大效果
  • ZoomOut
    - 缩小效果
  • None
    - 无动画
示例:自定义动画
jsx
import React, { useRef } from 'react';
import { TabComponent, TabItemsDirective, TabItemDirective } from '@syncfusion/ej2-react-navigations';

export default function AnimationExample() {
  const tabRef = useRef(null);

  const animationSettings = {
    previous: { effect: 'SlideLeftIn', duration: 600, easing: 'ease' },
    next: { effect: 'SlideRightIn', duration: 600, easing: 'ease' }
  };

  return (
    <TabComponent ref={tabRef} animation={animationSettings}>
      <TabItemsDirective>
        <TabItemDirective header={{ text: 'Twitter' }} content="Twitter is an online social networking service..." />
        <TabItemDirective header={{ text: 'Facebook' }} content="Facebook is an online social networking service..." />
        <TabItemDirective header={{ text: 'WhatsApp' }} content="WhatsApp Messenger is a proprietary cross-platform instant messaging client..." />
      </TabItemsDirective>
    </TabComponent>
  );
}
示例:禁用动画
jsx
import React from 'react';
import { TabComponent, TabItemsDirective, TabItemDirective } from '@syncfusion/ej2-react-navigations';

export default function NoAnimationExample() {
  const animationSettings = {
    previous: { effect: 'None' },
    next: { effect: 'None' }
  };

  return (
    <TabComponent animation={animationSettings}>
      <TabItemsDirective>
        <TabItemDirective header={{ text: 'Tab 1' }} content="Content 1" />
        <TabItemDirective header={{ text: 'Tab 2' }} content="Content 2" />
      </TabItemsDirective>
    </TabComponent>
  );
}

HTML Sanitization

HTML内容清理

Protect against XSS attacks by enabling HTML sanitization. The
enableHtmlSanitizer
property controls whether untrusted HTML is sanitized.
Example: HTML Sanitization
jsx
import React from 'react';
import { TabComponent, TabItemsDirective, TabItemDirective } from '@syncfusion/ej2-react-navigations';

export default function HtmlSanitizationExample() {
  return (
    <div>
      {/* Sanitization enabled (default) - malicious scripts are removed */}
      <h2>With Sanitization (Safe)</h2>
      <TabComponent enableHtmlSanitizer={true}>
        <TabItemsDirective>
          <TabItemDirective 
            header={{ text: 'Safe Content' }} 
            content="<b>Bold text</b> - This is safe HTML"
          />
          <TabItemDirective 
            header={{ text: 'Dangerous Script' }} 
            content="<img src=x onerror='alert(\"XSS\")' /> - Script will be removed"
          />
        </TabItemsDirective>
      </TabComponent>

      {/* Sanitization disabled - use only with trusted content */}
      <h2>Without Sanitization (Use with Caution)</h2>
      <TabComponent enableHtmlSanitizer={false}>
        <TabItemsDirective>
          <TabItemDirective 
            header={{ text: 'Trusted Content Only' }} 
            content="<b>Only use when content is from trusted sources</b>"
          />
        </TabItemsDirective>
      </TabComponent>
    </div>
  );
}
通过启用HTML内容清理来防范XSS攻击,
enableHtmlSanitizer
属性控制是否清理不可信HTML内容。
示例:HTML内容清理
jsx
import React from 'react';
import { TabComponent, TabItemsDirective, TabItemDirective } from '@syncfusion/ej2-react-navigations';

export default function HtmlSanitizationExample() {
  return (
    <div>
      {/* 启用内容清理(默认)- 恶意脚本会被移除 */}
      <h2>With Sanitization (Safe)</h2>
      <TabComponent enableHtmlSanitizer={true}>
        <TabItemsDirective>
          <TabItemDirective 
            header={{ text: 'Safe Content' }} 
            content="<b>Bold text</b> - This is safe HTML"
          />
          <TabItemDirective 
            header={{ text: 'Dangerous Script' }} 
            content="<img src=x onerror='alert(\"XSS\")' /> - Script will be removed"
          />
        </TabItemsDirective>
      </TabComponent>

      {/* 禁用内容清理 - 仅用于可信内容 */}
      <h2>Without Sanitization (Use with Caution)</h2>
      <TabComponent enableHtmlSanitizer={false}>
        <TabItemsDirective>
          <TabItemDirective 
            header={{ text: 'Trusted Content Only' }} 
            content="<b>Only use when content is from trusted sources</b>"
          />
        </TabItemsDirective>
      </TabComponent>
    </div>
  );
}

State Persistence

状态持久化

The
enablePersistence
property allows the Tab component to persist the selected tab across page reloads.
Example: State Persistence
jsx
import React from 'react';
import { TabComponent, TabItemsDirective, TabItemDirective } from '@syncfusion/ej2-react-navigations';

export default function PersistenceExample() {
  return (
    <div>
      <p>
        Select a different tab and refresh the page. 
        The previously selected tab will be restored.
      </p>
      <TabComponent enablePersistence={true} selectedItem={0}>
        <TabItemsDirective>
          <TabItemDirective header={{ text: 'Twitter' }} content="Twitter is an online social networking service that enables users to send and read short 140-character messages..." />
          <TabItemDirective header={{ text: 'Facebook' }} content="Facebook is an online social networking service headquartered in Menlo Park, California..." />
          <TabItemDirective header={{ text: 'WhatsApp' }} content="WhatsApp Messenger is a proprietary cross-platform instant messaging client for smartphones..." />
        </TabItemsDirective>
      </TabComponent>
    </div>
  );
}
Persisted State:
  • selectedItem
    - The index of the currently active tab
The persistence uses browser local storage to save and restore the state.
enablePersistence
属性允许Tab组件跨页面重载持久化选中选项卡的状态。
示例:状态持久化
jsx
import React from 'react';
import { TabComponent, TabItemsDirective, TabItemDirective } from '@syncfusion/ej2-react-navigations';

export default function PersistenceExample() {
  return (
    <div>
      <p>
        Select a different tab and refresh the page. 
        The previously selected tab will be restored.
      </p>
      <TabComponent enablePersistence={true} selectedItem={0}>
        <TabItemsDirective>
          <TabItemDirective header={{ text: 'Twitter' }} content="Twitter is an online social networking service that enables users to send and read short 140-character messages..." />
          <TabItemDirective header={{ text: 'Facebook' }} content="Facebook is an online social networking service headquartered in Menlo Park, California..." />
          <TabItemDirective header={{ text: 'WhatsApp' }} content="WhatsApp Messenger is a proprietary cross-platform instant messaging client for smartphones..." />
        </TabItemsDirective>
      </TabComponent>
    </div>
  );
}
持久化状态:
  • selectedItem
    - 当前激活选项卡的索引
状态持久化使用浏览器本地存储来保存和恢复状态。

Swipe Navigation

滑动导航

The
swipeMode
property enables or disables tab navigation using swipe gestures. This is particularly useful for mobile devices and touch interfaces, but can be customized to prevent accidental swipes.
SwipeMode Options:
  • Both
    (default) - Allows swipe with both touch and mouse
  • Touch
    - Allows swipe with touch gestures only
  • Mouse
    - Allows swipe with mouse gestures only
  • None
    - Disables swipe navigation completely
Example: Disable Swipe to Prevent Accidental Tab Changes
jsx
import React from 'react';
import { TabComponent, TabItemsDirective, TabItemDirective } from '@syncfusion/ej2-react-navigations';

export default function SwipeModeExample() {
  return (
    <div>
      <h3>Form Tab - Swipe Disabled to Prevent Data Loss</h3>
      <TabComponent heightAdjustMode='Auto' swipeMode='None'>
        <TabItemsDirective>
          <TabItemDirective 
            header={{ text: 'Personal Info' }} 
            content="Fill out your personal information without accidental swipes"
          />
          <TabItemDirective 
            header={{ text: 'Address' }} 
            content="Enter your address details"
          />
          <TabItemDirective 
            header={{ text: 'Confirmation' }} 
            content="Review and confirm your information"
          />
        </TabItemsDirective>
      </TabComponent>

      <h3>Mobile Navigation - Touch Swipe Only</h3>
      <TabComponent swipeMode='Touch'>
        <TabItemsDirective>
          <TabItemDirective 
            header={{ text: 'Twitter' }} 
            content="Twitter content - Swipe on mobile only"
          />
          <TabItemDirective 
            header={{ text: 'Facebook' }} 
            content="Facebook content - Swipe on mobile only"
          />
          <TabItemDirective 
            header={{ text: 'WhatsApp' }} 
            content="WhatsApp content - Swipe on mobile only"
          />
        </TabItemsDirective>
      </TabComponent>
    </div>
  );
}
Example: Disable Swipe for Mouse, Allow Touch
jsx
import React from 'react';
import { TabComponent, TabItemsDirective, TabItemDirective } from '@syncfusion/ej2-react-navigations';

export default function TouchSwipeExample() {
  return (
    <TabComponent swipeMode='Touch'>
      <TabItemsDirective>
        <TabItemDirective 
          header={{ text: 'Dashboard' }} 
          content="Dashboard content - Swipe available on touch devices"
        />
        <TabItemDirective 
          header={{ text: 'Analytics' }} 
          content="Analytics content"
        />
      </TabItemsDirective>
    </TabComponent>
  );
}
swipeMode
属性启用或禁用通过滑动手势切换选项卡,这在移动设备和触摸界面上尤为实用,也可自定义以防止误触。
SwipeMode选项:
  • Both
    (默认)- 允许触摸和鼠标滑动
  • Touch
    - 仅允许触摸手势滑动
  • Mouse
    - 仅允许鼠标手势滑动
  • None
    - 完全禁用滑动导航
示例:禁用滑动以防止误触
jsx
import React from 'react';
import { TabComponent, TabItemsDirective, TabItemDirective } from '@syncfusion/ej2-react-navigations';

export default function SwipeModeExample() {
  return (
    <div>
      <h3>Form Tab - Swipe Disabled to Prevent Data Loss</h3>
      <TabComponent heightAdjustMode='Auto' swipeMode='None'>
        <TabItemsDirective>
          <TabItemDirective 
            header={{ text: 'Personal Info' }} 
            content="Fill out your personal information without accidental swipes"
          />
          <TabItemDirective 
            header={{ text: 'Address' }} 
            content="Enter your address details"
          />
          <TabItemDirective 
            header={{ text: 'Confirmation' }} 
            content="Review and confirm your information"
          />
        </TabItemsDirective>
      </TabComponent>

      <h3>Mobile Navigation - Touch Swipe Only</h3>
      <TabComponent swipeMode='Touch'>
        <TabItemsDirective>
          <TabItemDirective 
            header={{ text: 'Twitter' }} 
            content="Twitter content - Swipe on mobile only"
          />
          <TabItemDirective 
            header={{ text: 'Facebook' }} 
            content="Facebook content - Swipe on mobile only"
          />
          <TabItemDirective 
            header={{ text: 'WhatsApp' }} 
            content="WhatsApp content - Swipe on mobile only"
          />
        </TabItemsDirective>
      </TabComponent>
    </div>
  );
}
示例:禁用鼠标滑动,允许触摸滑动
jsx
import React from 'react';
import { TabComponent, TabItemsDirective, TabItemDirective } from '@syncfusion/ej2-react-navigations';

export default function TouchSwipeExample() {
  return (
    <TabComponent swipeMode='Touch'>
      <TabItemsDirective>
        <TabItemDirective 
          header={{ text: 'Dashboard' }} 
          content="Dashboard content - Swipe available on touch devices"
        />
        <TabItemDirective 
          header={{ text: 'Analytics' }} 
          content="Analytics content"
        />
      </TabItemsDirective>
    </TabComponent>
  );
}

Tab Scroll Step Customization

选项卡滚动步长自定义

The
scrollStep
property controls the distance (in pixels) that tab headers scroll when you click the left and right navigation arrows. This is useful for fine-tuning the scroll behavior when tabs overflow.
Example: Custom Scroll Step
jsx
import React from 'react';
import { TabComponent, TabItemsDirective, TabItemDirective } from '@syncfusion/ej2-react-navigations';

export default function ScrollStepExample() {
  const htmlContent = () => {
    return <div>
      HyperText Markup Language, commonly referred to as HTML, is the standard markup language used to create web pages.
    </div>;
  };
  const csharpContent = () => {
    return <div>
      C# is intended to be a simple, modern, general-purpose, object-oriented programming language.
    </div>;
  };
  const javaContent = () => {
    return <div>
      Java is a set of computer software and specifications developed by Sun Microsystems.
    </div>;
  };
  const vbNetContent = () => {
    return <div>
      The command-line compiler, VBC.EXE, is installed as part of the freeware .NET Framework SDK.
    </div>;
  };
  const xamarinContent = () => {
    return <div>
      Xamarin is a software company created in May 2011 by the engineers that created Mono.
    </div>;
  };
  const aspNetcontent = () => {
    return <div>
      ASP.NET is an open-source server-side web application framework designed for web development.
    </div>;
  };
  const mvcContent = () => {
    return <div>
      The ASP.NET MVC is a web application framework developed by Microsoft.
    </div>;
  };
  const jsContent = () => {
    return <div>
      JavaScript (JS) is an interpreted computer programming language.
    </div>;
  };

  return (
    <div>
      <h3>Tab Scroll Step: 50px per click</h3>
      <p>Click the left/right navigation arrows - tabs scroll 50 pixels at a time</p>
      
      <TabComponent height="250px" scrollStep={50}>
        <TabItemsDirective>
          <TabItemDirective header={{ text: 'HTML' }} content={htmlContent} />
          <TabItemDirective header={{ text: 'C#' }} content={csharpContent} />
          <TabItemDirective header={{ text: 'Java' }} content={javaContent} />
          <TabItemDirective header={{ text: 'VB.Net' }} content={vbNetContent} />
          <TabItemDirective header={{ text: 'Xamarin' }} content={xamarinContent} />
          <TabItemDirective header={{ text: 'ASP.NET' }} content={aspNetcontent} />
          <TabItemDirective header={{ text: 'ASP.NET MVC' }} content={mvcContent} />
          <TabItemDirective header={{ text: 'JavaScript' }} content={jsContent} />
        </TabItemsDirective>
      </TabComponent>

      <h3>Tab Scroll Step: 100px per click (Faster)</h3>
      <p>Larger scroll step for quicker tab navigation</p>
      
      <TabComponent height="250px" scrollStep={100}>
        <TabItemsDirective>
          <TabItemDirective header={{ text: 'HTML' }} content={htmlContent} />
          <TabItemDirective header={{ text: 'C#' }} content={csharpContent} />
          <TabItemDirective header={{ text: 'Java' }} content={javaContent} />
          <TabItemDirective header={{ text: 'VB.Net' }} content={vbNetContent} />
          <TabItemDirective header={{ text: 'Xamarin' }} content={xamarinContent} />
          <TabItemDirective header={{ text: 'ASP.NET' }} content={aspNetcontent} />
          <TabItemDirective header={{ text: 'ASP.NET MVC' }} content={mvcContent} />
          <TabItemDirective header={{ text: 'JavaScript' }} content={jsContent} />
        </TabItemsDirective>
      </TabComponent>
    </div>
  );
}
scrollStep
属性控制点击左右导航箭头时选项卡标题的滚动距离(像素),用于在选项卡溢出时微调滚动行为。
示例:自定义滚动步长
jsx
import React from 'react';
import { TabComponent, TabItemsDirective, TabItemDirective } from '@syncfusion/ej2-react-navigations';

export default function ScrollStepExample() {
  const htmlContent = () => {
    return <div>
      HyperText Markup Language, commonly referred to as HTML, is the standard markup language used to create web pages.
    </div>;
  };
  const csharpContent = () => {
    return <div>
      C# is intended to be a simple, modern, general-purpose, object-oriented programming language.
    </div>;
  };
  const javaContent = () => {
    return <div>
      Java is a set of computer software and specifications developed by Sun Microsystems.
    </div>;
  };
  const vbNetContent = () => {
    return <div>
      The command-line compiler, VBC.EXE, is installed as part of the freeware .NET Framework SDK.
    </div>;
  };
  const xamarinContent = () => {
    return <div>
      Xamarin is a software company created in May 2011 by the engineers that created Mono.
    </div>;
  };
  const aspNetcontent = () => {
    return <div>
      ASP.NET is an open-source server-side web application framework designed for web development.
    </div>;
  };
  const mvcContent = () => {
    return <div>
      The ASP.NET MVC is a web application framework developed by Microsoft.
    </div>;
  };
  const jsContent = () => {
    return <div>
      JavaScript (JS) is an interpreted computer programming language.
    </div>;
  };

  return (
    <div>
      <h3>Tab Scroll Step: 50px per click</h3>
      <p>Click the left/right navigation arrows - tabs scroll 50 pixels at a time</p>
      
      <TabComponent height="250px" scrollStep={50}>
        <TabItemsDirective>
          <TabItemDirective header={{ text: 'HTML' }} content={htmlContent} />
          <TabItemDirective header={{ text: 'C#' }} content={csharpContent} />
          <TabItemDirective header={{ text: 'Java' }} content={javaContent} />
          <TabItemDirective header={{ text: 'VB.Net' }} content={vbNetContent} />
          <TabItemDirective header={{ text: 'Xamarin' }} content={xamarinContent} />
          <TabItemDirective header={{ text: 'ASP.NET' }} content={aspNetcontent} />
          <TabItemDirective header={{ text: 'ASP.NET MVC' }} content={mvcContent} />
          <TabItemDirective header={{ text: 'JavaScript' }} content={jsContent} />
        </TabItemsDirective>
      </TabComponent>

      <h3>Tab Scroll Step: 100px per click (Faster)</h3>
      <p>Larger scroll step for quicker tab navigation</p>
      
      <TabComponent height="250px" scrollStep={100}>
        <TabItemsDirective>
          <TabItemDirective header={{ text: 'HTML' }} content={htmlContent} />
          <TabItemDirective header={{ text: 'C#' }} content={csharpContent} />
          <TabItemDirective header={{ text: 'Java' }} content={javaContent} />
          <TabItemDirective header={{ text: 'VB.Net' }} content={vbNetContent} />
          <TabItemDirective header={{ text: 'Xamarin' }} content={xamarinContent} />
          <TabItemDirective header={{ text: 'ASP.NET' }} content={aspNetcontent} />
          <TabItemDirective header={{ text: 'ASP.NET MVC' }} content={mvcContent} />
          <TabItemDirective header={{ text: 'JavaScript' }} content={jsContent} />
        </TabItemsDirective>
      </TabComponent>
    </div>
  );
}

Advanced Settings: CSS Classes and RTL

高级设置:CSS类与RTL布局

Custom CSS Classes
Apply custom styling using the
cssClass
property:
jsx
import React from 'react';
import { TabComponent, TabItemsDirective, TabItemDirective } from '@syncfusion/ej2-react-navigations';
import './CustomTab.css';

export default function CustomCssExample() {
  return (
    <TabComponent cssClass="custom-tab-theme">
      <TabItemsDirective>
        <TabItemDirective header={{ text: 'Tab 1' }} content="Content 1" />
        <TabItemDirective header={{ text: 'Tab 2' }} content="Content 2" />
      </TabItemsDirective>
    </TabComponent>
  );
}
RTL (Right-to-Left) Support
Enable RTL layout for Arabic, Hebrew, and other RTL languages:
jsx
import React from 'react';
import { TabComponent, TabItemsDirective, TabItemDirective } from '@syncfusion/ej2-react-navigations';

export default function RTLExample() {
  return (
    <TabComponent enableRtl={true}>
      <TabItemsDirective>
        <TabItemDirective header={{ text: 'ملخص' }} content="محتوى في اللغة العربية" />
        <TabItemDirective header={{ text: 'تفاصيل' }} content="المزيد من المحتوى" />
        <TabItemDirective header={{ text: 'الإعدادات' }} content="إعدادات التطبيق" />
      </TabItemsDirective>
    </TabComponent>
  );
}
Combined Advanced Example
jsx
import React, { useRef } from 'react';
import { TabComponent, TabItemsDirective, TabItemDirective } from '@syncfusion/ej2-react-navigations';

export default function AdvancedSettingsExample() {
  const tabRef = useRef(null);

  const handleTabSelecting = (args) => {
    console.log(`Switching from tab ${args.previousIndex} to tab ${args.selectedIndex}`);
  };

  const animationSettings = {
    previous: { effect: 'SlideLeftIn', duration: 500, easing: 'ease-out' },
    next: { effect: 'SlideRightIn', duration: 500, easing: 'ease-out' }
  };

  return (
    <TabComponent
      ref={tabRef}
      headerPlacement="Top"
      overflowMode="Scrollable"
      enablePersistence={true}
      enableHtmlSanitizer={true}
      enableRtl={false}
      cssClass="advanced-tab-demo"
      animation={animationSettings}
      heightAdjustMode="Auto"
      selecting={handleTabSelecting}
    >
      <TabItemsDirective>
        <TabItemDirective 
          header={{ text: 'Overview', iconCss: 'e-icons e-home' }} 
          content="Welcome to the overview tab" 
        />
        <TabItemDirective 
          header={{ text: 'Profile', iconCss: 'e-icons e-user' }} 
          content="User profile information" 
        />
        <TabItemDirective 
          header={{ text: 'Settings', iconCss: 'e-icons e-settings' }} 
          content="Application settings" 
        />
      </TabItemsDirective>
    </TabComponent>
  );
}
自定义CSS类
使用
cssClass
属性应用自定义样式:
jsx
import React from 'react';
import { TabComponent, TabItemsDirective, TabItemDirective } from '@syncfusion/ej2-react-navigations';
import './CustomTab.css';

export default function CustomCssExample() {
  return (
    <TabComponent cssClass="custom-tab-theme">
      <TabItemsDirective>
        <TabItemDirective header={{ text: 'Tab 1' }} content="Content 1" />
        <TabItemDirective header={{ text: 'Tab 2' }} content="Content 2" />
      </TabItemsDirective>
    </TabComponent>
  );
}
RTL(从右到左)支持
为阿拉伯语、希伯来语等RTL语言启用RTL布局:
jsx
import React from 'react';
import { TabComponent, TabItemsDirective, TabItemDirective } from '@syncfusion/ej2-react-navigations';

export default function RTLExample() {
  return (
    <TabComponent enableRtl={true}>
      <TabItemsDirective>
        <TabItemDirective header={{ text: 'ملخص' }} content="محتوى في اللغة العربية" />
        <TabItemDirective header={{ text: 'تفاصيل' }} content="المزيد من المحتوى" />
        <TabItemDirective header={{ text: 'الإعدادات' }} content="إعدادات التطبيق" />
      </TabItemsDirective>
    </TabComponent>
  );
}
综合高级示例
jsx
import React, { useRef } from 'react';
import { TabComponent, TabItemsDirective, TabItemDirective } from '@syncfusion/ej2-react-navigations';

export default function AdvancedSettingsExample() {
  const tabRef = useRef(null);

  const handleTabSelecting = (args) => {
    console.log(`Switching from tab ${args.previousIndex} to tab ${args.selectedIndex}`);
  };

  const animationSettings = {
    previous: { effect: 'SlideLeftIn', duration: 500, easing: 'ease-out' },
    next: { effect: 'SlideRightIn', duration: 500, easing: 'ease-out' }
  };

  return (
    <TabComponent
      ref={tabRef}
      headerPlacement="Top"
      overflowMode="Scrollable"
      enablePersistence={true}
      enableHtmlSanitizer={true}
      enableRtl={false}
      cssClass="advanced-tab-demo"
      animation={animationSettings}
      heightAdjustMode="Auto"
      selecting={handleTabSelecting}
    >
      <TabItemsDirective>
        <TabItemDirective 
          header={{ text: 'Overview', iconCss: 'e-icons e-home' }} 
          content="Welcome to the overview tab" 
        />
        <TabItemDirective 
          header={{ text: 'Profile', iconCss: 'e-icons e-user' }} 
          content="User profile information" 
        />
        <TabItemDirective 
          header={{ text: 'Settings', iconCss: 'e-icons e-settings' }} 
          content="Application settings" 
        />
      </TabItemsDirective>
    </TabComponent>
  );
}

Related Skills

相关技能

  • Implementing Accordion - Similar navigation component for collapsible content
  • Implementing Sidebars - Complementary navigation pattern
  • Implementing Breadcrumbs - Navigation context alongside tabs
undefined
  • 实现Accordion组件 - 用于可折叠内容的类似导航组件
  • 实现侧边栏 - 互补的导航模式
  • 实现面包屑导航 - 与选项卡搭配的导航上下文组件
undefined