syncfusion-react-context-menu について
Syncfusion ContextMenu コンポーネントを使う React 開発者向けのリファレンスです。設定やイベント、実行時管理に加え、入れ子メニュー、テンプレート、アクセシビリティ、項目の動的な表示・更新を扱います。
主な機能
- 01入れ子項目とセパレーター
- 02対象要素によるメニュー表示
- 03テンプレートとアニメーション設定
- 04メニュー項目の動的管理
- 05イベント処理とキーボード操作
- 06RTL レイアウトと HTML サニタイズ
活用シーン
- 01ファイルの右クリック操作の追加
- 02状況に応じた操作項目の表示
- 03権限に応じた項目の非表示・無効化
- 04サブメニュー付き操作メニューの作成
インストール
コマンドをコピーしてターミナルで実行します。
npx skills add https:/ / github.com/ syncfusion/ react-ui-components-skills --skill syncfusion-react-context-menuインストール後、Claude Code で/syncfusion-react-context-menuを入力して読み込まれたか確認します。
同梱ファイル
SKILL.md と一緒にインストールされる参考資料やスクリプト。
references/accessibility-and-keyboard-navigation.mdadvanced-features.mdevents-and-interaction.mdgetting-started.mdmenu-items-and-data-binding.mdstyling-and-appearance.mdtemplates-and-customization.mduse-cases-and-patterns.md詳細
Syncfusion React Context Menu の実装
API リファレンスと機能ガイドの完全版
このスキルを使用するタイミング
ユーザーが次のことを行う場合は、必ずこのスキルを使用してください。
- インストールして設定する Syncfusion React ContextMenu コンポーネント
- メニュー項目を作成、管理する(テキスト、アイコン、区切り線、ネストされたメニュー、URL)
- 15 以上のメソッドを使ってメニューをプログラムから制御する
- それぞれのイベント引数とともに、7 つすべてのイベントを処理する
- CSS クラス、テーマ、テンプレート、アニメーションを使って外観をカスタマイズする
- ローカルソースまたは動的なデータ構造からデータをバインドする
- アクセシビリティを実装する(キーボードナビゲーション、ARIA、RTL、WCAG 2.2)
- 動的メニューを管理する(追加、削除、表示、非表示、有効化/無効化)
- コンテキストに応じたアクションを作成する(ファイル、エディター、ワークフロー)
はじめに
📄 参照: references/getting-started.md
- パッケージのインストール(
@syncfusion/ej2-react-navigations) - 開発環境のセットアップ(Vite、Create React App)
- CSS スタイルシートのインポートとテーマの設定
- 基本的な ContextMenu の実装
- アプリケーションの実行とテスト
コンポーネントのプロパティリファレンス
ContextMenuComponent は、動作、外観、インタラクションを制御する 18 個以上の設定プロパティを受け付けます。
主要なプロパティ
target(必須)
型: string
コンテキストメニューを起動する要素(右クリックまたは長押し)の CSS セレクターです。
<ContextMenuComponent target="#myElement" items={menuItems} />
例: 特定の要素で起動する
function App() {
return (
<div>
<div id="target">Right-click here</div>
<ContextMenuComponent target="#target" items={menuItems} />
</div>
);
}
items(必須)
型: MenuItemModel[]
表示するメニュー項目の配列です。各項目には、テキスト、アイコン、ネストされた項目、区切り線などを設定できます。
const menuItems: MenuItemModel[] = [
{ text: 'Cut' },
{ text: 'Copy' },
{ text: 'Paste' },
{ separator: true },
{
text: 'More',
items: [
{ text: 'Properties' },
{ text: 'Delete' }
]
}
];
<ContextMenuComponent target="#target" items={menuItems} />
表示とアニメーションのプロパティ
animationSettings
型: MenuAnimationSettingsModel
メニューを開閉する際のアニメーション効果を設定します。
プロパティ:
effect: アニメーションの種類(None、SlideDown、ZoomIn、FadeIn)duration: アニメーション時間(ミリ秒、既定値は 400)easing: CSS のイージング関数(既定値は ease)
const animationSettings = {
effect: 'FadeIn',
duration: 300,
easing: 'ease-out'
};
<ContextMenuComponent
target="#target"
items={menuItems}
animationSettings={animationSettings}
/>
利用可能な効果:
| 効果 | 説明 |
|---|---|
None | アニメーションなし |
SlideDown | 上からスライドして表示 |
ZoomIn | ズームイン効果 |
FadeIn | 不透明度が徐々に上がる |
cssClass
型: string
カスタムスタイルを適用するため、ContextMenu のラッパーにカスタム CSS クラスを追加します。
<ContextMenuComponent
target="#target"
items={menuItems}
cssClass="custom-menu dark-theme"
/>
enableScrolling
型: boolean(既定値: false)
メニューの高さが利用可能なスペースを超えた場合に、スクロールを有効にします。
<ContextMenuComponent
target="#target"
items={largeMenuList}
enableScrolling={true}
/>
インタラクションのプロパティ
filter
型: string
コンテキストメニューを起動する、ターゲット内の特定の要素を指定する CSS セレクターです。コンテキストメニューを特定の子要素に限定する場合に使用します。
// Context menu only appears on table rows, not the entire table
<ContextMenuComponent
target="#table"
filter="tr"
items={menuItems}
/>
hoverDelay
型: number(既定値: 400)
ホバー時にサブメニューを表示するまでの待機時間(ミリ秒)です。
<ContextMenuComponent
target="#target"
items={menuItems}
hoverDelay={500} // 500ms before submenu appears
/>
showItemOnClick
型: boolean(既定値: false)
サブメニューをクリック時のみ開くようにします(ホバーでは開きません)。true の場合、サブメニューを開くには矢印キーでのナビゲーションが必要です。
<ContextMenuComponent
target="#target"
items={menuItems}
showItemOnClick={true} // Submenus open on click only
/>
データとコンテンツのプロパティ
itemTemplate
型: string | Function
メニュー項目用のカスタム HTML テンプレートです。プロパティのプレースホルダー(${propertyName})を含むテンプレート文字列を使用します。
const template = `
<div class="menu-item">
<span class="${iconCss}"></span>
<span>${text}</span>
<span class="shortcut">${shortcut}</span>
</div>
`;
<ContextMenuComponent
target="#target"
items={menuItems}
itemTemplate={template}
/>
locale
型: string(既定値: 'en-US')
コンポーネントのローカライズ言語を設定します。グローバルなカルチャー設定を上書きします。
<ContextMenuComponent
target="#target"
items={menuItems}
locale="es-ES" // Spanish localization
/>
セキュリティと状態のプロパティ
enableHtmlSanitizer
型: boolean(既定値: true)
XSS 攻撃を防ぐため、HTML サニタイズを有効にします。メニュー項目内の信頼できない HTML をサニタイズします。
<ContextMenuComponent
target="#target"
items={menuItems}
enableHtmlSanitizer={true} // Sanitize HTML content
/>
enablePersistence
型: boolean(既定値: false)
ブラウザーのストレージを使用して、ページの再読み込み後もコンポーネントの状態(展開/折りたたみ状態)を保持します。
<ContextMenuComponent
target="#target"
items={menuItems}
enablePersistence={true}
/>
enableRtl
型: boolean(既定値: false)
アラビア語、ヘブライ語などの右から左(RTL)に記述する言語向けのレイアウトを有効にします。
<ContextMenuComponent
target="#target"
items={menuItems}
enableRtl={true}
/>
メニュー項目モデルのプロパティ
各メニュー項目は、MenuItemModel インターフェイスを使用して、次のプロパティを設定します。
テキストと表示
text
型: string
メニュー項目に表示するテキストです。
{ text: 'Cut' }
{ text: 'Copy' }
id
型: string
メニュー項目の一意な識別子です。イベントハンドラーやプログラムによる操作で項目を識別する際に使用します。
{ id: 'cut-item', text: 'Cut' }
{ id: 'copy-item', text: 'Copy' }
iconCss
型: string
アイコン表示に使用する CSS クラスです。Syncfusion のアイコンまたはカスタムアイコンクラスに対応しています。
{ text: 'Cut', iconCss: 'e-icons e-cut' }
{ text: 'Copy', iconCss: 'e-icons e-copy' }
{ text: 'Delete', iconCss: 'e-icons e-delete' }
項目の構造
items
型: MenuItemModel[]
ネストされたサブメニュー項目です。階層構造のメニューを作成します。
{
text: 'File',
items: [
{ text: 'New' },
{ text: 'Open' },
{ text: 'Save' }
]
}
separator
型: boolean(デフォルト:false)
クリック可能な項目ではなく、視覚的な区切り線として表示します。
const menuItems: MenuItemModel[] = [
{ text: 'Cut' },
{ text: 'Copy' },
{ separator: true }, // Visual divider
{ text: 'Delete' }
];
ナビゲーション
url
型: string
ナビゲーション URL です。クリックすると移動するアンカーリンクを作成します。
{ text: 'Visit Site', url: 'https://example.com' }
{ text: 'Documentation', url: '/docs' }
カスタム属性
htmlAttributes
型: Record<string, string>
メニュー項目の要素にカスタム HTML 属性を追加します。
{
text: 'Download',
htmlAttributes: {
'data-action': 'download',
'aria-label': 'Download file',
'title': 'Download the file'
}
}
メニューのメソッド ― プログラムによる制御
ContextMenu には、実行時の制御と操作に使用できる 15 個以上のメソッドがあります。
メニュー状態の制御
open(top: number, left: number, target?: HTMLElement): void
指定した座標でコンテキストメニューをプログラムから開きます。
パラメーター:
top:垂直位置(ピクセル単位の Y 座標)left:水平位置(ピクセル単位の X 座標)target:z-index の計算に使用する省略可能な HTML 要素
function App() {
const menuRef = React.useRef<ContextMenuComponent>(null);
const openMenuAtClick = (event: React.MouseEvent) => {
menuRef.current?.open(event.clientY, event.clientX);
};
return (
<div>
<button onClick={openMenuAtClick}>Open Menu</button>
<ContextMenuComponent ref={menuRef} target="#target" items={menuItems} />
</div>
);
}
close(): void
コンテキストメニューをプログラムから閉じます。
function App() {
const menuRef = React.useRef<ContextMenuComponent>(null);
const closeMenu = () => {
menuRef.current?.close();
};
const handleItemSelect = (args: MenuEventArgs) => {
console.log('Selected:', args.item?.text);
closeMenu(); // Close menu after selection
};
return (
<ContextMenuComponent
ref={menuRef}
target="#target"
items={menuItems}
select={handleItemSelect}
/>
);
}
項目の表示制御
showItems(items: string[], isUniqueId?: boolean): void
以前に非表示にしたメニュー項目を表示します。
パラメーター:
items:表示する項目のテキストまたは ID の配列isUniqueId:true の場合、項目を一意な ID として扱います。false の場合、テキストとして扱います(デフォルト:false)
function App() {
const menuRef = React.useRef<ContextMenuComponent>(null);
const showDeleteOption = () => {
menuRef.current?.showItems(['Delete', 'Rename']);
};
return (
<div>
<button onClick={showDeleteOption}>Show Options</button>
<ContextMenuComponent ref={menuRef} target="#target" items={menuItems} />
</div>
);
}
hideItems(items: string[], isUniqueId?: boolean): void
メニュー構造内に項目を残したまま、特定のメニュー項目を非表示にします。
パラメーター:
items:非表示にする項目のテキストまたは ID の配列isUniqueId:true の場合、項目を一意な ID として扱います
function App() {
const menuRef = React.useRef<ContextMenuComponent>(null);
React.useEffect(() => {
// Hide delete option for read-only mode
if (isReadOnly) {
menuRef.current?.hideItems(['Delete', 'Modify']);
}
}, [isReadOnly]);
return (
<ContextMenuComponent ref={menuRef} target="#target" items={menuItems} />
);
}
項目の状態管理
enableItems(items: string[], enable: boolean, isUniqueId?: boolean): void
メニュー項目を有効または無効にして、操作の可否を制御します。
パラメーター:
items:変更する項目のテキストまたは ID の配列enable:有効にする場合は true、無効にする場合は falseisUniqueId:true の場合、項目を一意な ID として扱います
function App() {
const menuRef = React.useRef<ContextMenuComponent>(null);
const disablePasteIfNoClipboard = async () => {
const canPaste = await navigator.permissions.query({ name: 'clipboard-read' });
if (canPaste.state === 'denied') {
menuRef.current?.enableItems(['Paste'], false);
}
};
React.useEffect(() => {
disablePasteIfNoClipboard();
}, []);
return (
<ContextMenuComponent
ref={menuRef}
target="#target"
items={menuItems}
beforeOpen={disablePasteIfNoClipboard}
/>
);
}
項目の操作
insertAfter(items: MenuItemModel[], text: string, isUniqueId?: boolean): void
指定した対象項目の後に新しいメニュー項目を挿入します。
パラメーター:
items:挿入する新しいMenuItemModel項目の配列text:挿入位置の基準とする項目のテキストまたは IDisUniqueId:true の場合、text を一意な ID として扱います
function App() {
const menuRef = React.useRef<ContextMenuComponent>(null);
const addSortByOption = () => {
const newItems: MenuItemModel[] = [
{ text: 'Sort By Name' },
{ text: 'Sort By Date' }
];
menuRef.current?.insertAfter(newItems, 'View');
};
return (
<div>
<button onClick={addSortByOption}>Add Sort Options</button>
<ContextMenuComponent ref={menuRef} target="#target" items={menuItems} />
</div>
);
}
insertBefore(items: MenuItemModel[], text: string, isUniqueId?: boolean): void
指定した対象項目の前に新しいメニュー項目を挿入します。
function App() {
const menuRef = React.useRef<ContextMenuComponent>(null);
const addPremiumOptions = () => {
const premiumItems: MenuItemModel[] = [
{ text: 'Premium Feature 1' },
{ text: 'Premium Feature 2', iconCss: 'e-icons e-star' }
];
// Insert before 'Delete' option
menuRef.current?.insertBefore(premiumItems, 'Delete');
};
React.useEffect(() => {
if (user.isPremium) {
addPremiumOptions();
}
}, [user.isPremium]);
return (
<ContextMenuComponent ref={menuRef} target="#target" items={menuItems} />
);
}
removeItems(items: string[], isUniqueId?: boolean): void
メニューから項目を削除します。
パラメーター:
items:削除する項目のテキストまたは ID の配列isUniqueId:true の場合、項目を一意な ID として扱います
function App() {
const menuRef = React.useRef<ContextMenuComponent>(null);
const removeRestrictedActions = () => {
menuRef.current?.removeItems(['Delete', 'Export', 'Archive']);
};
React.useEffect(() => {
if (userRole === 'viewer') {
removeRestrictedActions();
}
}, [userRole]);
return (
<ContextMenuComponent
ref={menuRef}
target="#target"
items={menuItems}
created={removeRestrictedActions}
/>
);
}
項目の検索
getItemIndex(item: MenuItem | string, isUniqueId?: boolean): number[]
メニュー項目のインデックスを取得します。項目は複数の階層に存在する場合があるため、配列を返します(ネストされた項目の場合)。
パラメーター:
item:検索するMenuItemオブジェクト、またはテキスト/ID の文字列isUniqueId:true の場合、項目を一意な ID として扱います
戻り値: number[] - 項目の位置を表すインデックス番号の配列
function App() {
const menuRef = React.useRef<ContextMenuComponent>(null);
const findItemPosition = () => {
const indices = menuRef.current?.getItemIndex('Copy');
console.log('Copy is at index:', indices); // Output: [1] or [0, 1] for nested
const nestedIndices = menuRef.current?.getItemIndex('Open', false);
console.log('Open is at indices:', nestedIndices); // Output: [0, 1] for nested
};
return (
<div>
<button onClick={findItemPosition}>Find Item</button>
<ContextMenuComponent ref={menuRef} target="#target" items={menuItems} />
</div>
);
}
setItem(item: MenuItem, id?: string, isUniqueId?: boolean): void
既存のメニュー項目のプロパティを更新します。
パラメーター:
item:更新されたプロパティを持つMenuItemオブジェクトid:更新する項目のテキストまたは IDisUniqueId:true の場合、id を一意な ID として扱います
function App() {
const menuRef = React.useRef<ContextMenuComponent>(null);
const updateDeleteItemStyle = () => {
const updatedItem: MenuItemModel = {
text: 'Delete',
iconCss: 'e-icons e-delete',
htmlAttributes: {
'class': 'dangerous-action'
}
};
menuRef.current?.setItem(updatedItem, 'Delete');
};
return (
<div>
<button onClick={updateDeleteItemStyle}>Update Delete Item</button>
<ContextMenuComponent ref={menuRef} target="#target" items={menuItems} />
</div>
);
}
コンポーネントのライフサイクル
destroy(): void
ContextMenu コンポーネントを破棄し、リソースを解放します。
function App() {
const menuRef = React.useRef<ContextMenuComponent>(null);
React.useEffect(() => {
return () => {
// Cleanup on component unmount
menuRef.current?.destroy();
};
}, []);
return (
<ContextMenuComponent ref={menuRef} target="#target" items={menuItems} />
);
}
イベントとイベント引数
ContextMenu コンポーネントは、ユーザー操作を監視および制御するための 7 つのイベントを提供します。
メニューのライフサイクルイベント
beforeOpen
型: EmitType<BeforeOpenCloseMenuEventArgs>
メニューが開く前に発生します。メニューを開かないようにしたり、項目を変更したり、データを準備したりする場合に使用します。
イベント引数:
interface BeforeOpenCloseMenuEventArgs {
element: HTMLElement; // Menu element
event: Event; // Browser event object
items: MenuItemModel[]; // Current menu items
cancel: boolean; // Set to true to prevent action
parentItem?: MenuItemModel; // Parent item if submenu
}
例:特定の条件でメニューが開かないようにする
function App() {
const handleBeforeOpen = (args: BeforeOpenCloseMenuEventArgs) => {
// Prevent opening on read-only elements
const target = args.event?.target as HTMLElement;
if (target?.classList.contains('read-only')) {
args.cancel = true; // Prevent menu from opening
return;
}
// Modify items before opening
const selectedText = window.getSelection()?.toString();
if (!selectedText) {
// Disable text-related operations if no text selected
args.items = args.items?.map(item => ({
...item,
disabled: ['Copy', 'Cut'].includes(item.text as string)
}));
}
};
return (
<ContextMenuComponent
target="#target"
items={menuItems}
beforeOpen={handleBeforeOpen}
/>
);
}
onOpen
型: EmitType<OpenCloseMenuEventArgs>
メニューが開いた後に発生します。UI の初期化や、メニューを開いた後の処理に使用します。
イベント引数:
interface OpenCloseMenuEventArgs {
element: HTMLElement; // Menu element
event: Event; // Browser event that triggered opening
items: MenuItemModel[]; // Current menu items
}
例:メニューを開いた後に初期化する
function App() {
const handleOnOpen = (args: OpenCloseMenuEventArgs) => {
console.log('Menu opened at:', new Date());
console.log('Number of items:', args.items?.length);
// Set focus to first menu item for accessibility
setTimeout(() => {
const firstItem = args.element?.querySelector('.e-menu-item');
(firstItem as HTMLElement)?.focus();
}, 0);
};
return (
<ContextMenuComponent
target="#target"
items={menuItems}
onOpen={handleOnOpen}
/>
);
}
beforeClose
型: EmitType<BeforeOpenCloseMenuEventArgs>
メニューが閉じる前に発生します。メニューを閉じないようにしたり、状態を保存したりする場合に使用します。
例:未保存の変更がある場合にメニューが閉じないようにする
function App() {
const [hasUnsavedChanges, setHasUnsavedChanges] = React.useState(false);
const handleBeforeClose = (args: BeforeOpenCloseMenuEventArgs) => {
if (hasUnsavedChanges) {
const confirmed = window.confirm('Unsaved changes. Close anyway?');
if (!confirmed) {
args.cancel = true; // Prevent menu from closing
}
}
};
return (
<ContextMenuComponent
target="#target"
items={menuItems}
beforeClose={handleBeforeClose}
/>
);
}
onClose
型: EmitType<OpenCloseMenuEventArgs>
メニューが閉じた後に発生します。クリーンアップや状態管理に使用します。
例:メニューが閉じた後にクリーンアップする
function App() {
const handleOnClose = (args: OpenCloseMenuEventArgs) => {
console.log('Menu closed');
// Clear temporary selections or states
document.querySelectorAll('.temp-highlight').forEach(el => {
el.classList.remove('temp-highlight');
});
};
return (
<ContextMenuComponent
target="#target"
items={menuItems}
onClose={handleOnClose}
/>
);
}
項目操作イベント
select
型: EmitType<MenuEventArgs>
メニュー項目がクリックまたは選択されたときに発生します。選択に基づいてアクションを実行する場合に使用します。
イベント引数:
interface MenuEventArgs {
element: HTMLElement; // Menu item element
event: Event; // Click/keyboard event
item?: MenuItemModel; // Selected menu item
items?: MenuItemModel[]; // All menu items
}
例:項目の選択時にアクションを実行する
function App() {
const handleSelect = (args: MenuEventArgs) => {
const itemText = args.item?.text;
switch (itemText) {
case 'Cut':
document.execCommand('cut');
console.log('Cut executed');
break;
case 'Copy':
document.execCommand('copy');
console.log('Copy executed');
break;
case 'Paste':
document.execCommand('paste');
console.log('Paste executed');
break;
case 'Delete':
if (confirm('Confirm delete?')) {
console.log('Delete executed');
}
break;
}
};
return (
<ContextMenuComponent
target="#target"
items={menuItems}
select={handleSelect}
/>
);
}
beforeItemRender
型: EmitType<MenuEventArgs>
各メニュー項目が描画される前に発生します。項目の外観をカスタマイズしたり、独自のロジックを追加したりする場合に使用します。
例:条件に応じて項目を無効にする
function App() {
const handleBeforeItemRender = (args: MenuEventArgs) => {
const itemText = args.item?.text;
// Disable delete if user doesn't have permission
if (itemText === 'Delete' && !userPermissions.canDelete) {
args.element?.classList.add('e-disabled');
}
// Highlight recent items
if (itemText?.startsWith('Recent:')) {
args.element?.classList.add('recent-item-highlight');
}
// Add keyboard shortcut indicator
const shortcuts: Record<string, string> = {
'Cut': 'Ctrl+X',
'Copy': 'Ctrl+C',
'Paste': 'Ctrl+V'
};
if (shortcuts[itemText as string]) {
const shortcutEl = document.createElement('span');
shortcutEl.className = 'shortcut-hint';
shortcutEl.textContent = shortcuts[itemText as string];
args.element?.appendChild(shortcutEl);
}
};
return (
<ContextMenuComponent
target="#target"
items={menuItems}
beforeItemRender={handleBeforeItemRender}
/>
);
}
コンポーネントのライフサイクル
created
型: EmitType<Event>
コンポーネントの作成と描画が完了した後に発生します。初期化に使用します。
例:作成後に初期化する
function App() {
const menuRef = React.useRef<ContextMenuComponent>(null);
const handleCreated = () => {
console.log('ContextMenu created and ready');
// Perform initial setup
menuRef.current?.enableItems(['Advanced Options'], userRole === 'admin');
// Add custom data to items
const items = menuRef.current?.items;
if (items) {
items.forEach((item, index) => {
item.id = `item-${index}`;
});
}
};
return (
<ContextMenuComponent
ref={menuRef}
target="#target"
items={menuItems}
created={handleCreated}
/>
);
}
メニュー項目とデータバインディング
📄 参照: references/menu-items-and-data-binding.md
- MenuItemModel を使用したメニュー項目の作成
- items プロパティの使用
- ローカルデータソースを使用したデータバインディング
- 配列からの動的なメニュー項目の生成
- ネストされたサブメニューの設定
テンプレートとカスタマイズ
📄 参照: references/templates-and-customization.md
- カスタム項目テンプレート(itemTemplate)
- メニュー項目でのリッチコンテンツの描画
- 項目をカスタマイズする beforeItemRender イベント
- 項目へのアイコンとメタデータの追加
- 条件付き描画
スタイルと外観
📄 参照: references/styling-and-appearance.md
- CSS クラスのカスタマイズ
- Theme Studio との連携
- メニュー要素へのカスタム CSS の適用
- アイコンのスタイルと配置
- 視覚的な状態(ホバー、選択、無効)
アクセシビリティとキーボードナビゲーション
📄 参照: references/accessibility-and-keyboard-navigation.md
- WCAG 2.2 および Section 508 への準拠
- スクリーンリーダーのサポートと ARIA 属性
- キーボードショートカット(Esc、Enter、矢印キー)
- 右から左への表示(RTL)のサポート
- フォーカス管理
高度な機能
📄 参照: references/advanced-features.md
- スクロール可能なコンテキストメニュー
- アニメーションの設定と効果
- メニューの表示方法と配置
- オーバーフロー処理と動的レイアウト
- 複雑なシナリオ向けの設定
ユースケースとパターン
📄 参照: references/use-cases-and-patterns.md
- 一般的なコンテキストメニューのパターン
- 項目の動的な追加/削除/有効化/無効化
- 項目間の区切り線の描画
- 複数レベルのネストの例
- 実際の統合シナリオ
クイックリファレンス
基本的なコードテンプレート
import { ContextMenuComponent, MenuItemModel } from '@syncfusion/ej2-react-navigations';
import * as React from 'react';
function App() {
const menuRef = React.useRef<ContextMenuComponent>(null);
const menuItems: MenuItemModel[] = [
{ text: 'Cut', iconCss: 'e-icons e-cut', id: 'cut' },
{ text: 'Copy', iconCss: 'e-icons e-copy', id: 'copy' },
{ text: 'Paste', iconCss: 'e-icons e-paste', id: 'paste' },
{ separator: true },
{
text: 'More',
items: [
{ text: 'Delete' },
{ text: 'Properties' }
]
}
];
const handleSelect = (args: any) => {
console.log('Selected:', args.item?.text);
};
const handleBeforeOpen = (args: any) => {
// Customize menu before opening
};
return (
<div>
<div id="target">Right-click me</div>
<ContextMenuComponent
ref={menuRef}
target="#target"
items={menuItems}
select={handleSelect}
beforeOpen={handleBeforeOpen}
animationSettings={{ effect: 'FadeIn', duration: 300 }}
enableScrolling={true}
/>
</div>
);
}
export default App;
よく使うメソッドのリファレンス
// Open menu at coordinates
menuRef.current?.open(100, 150);
// Close menu
menuRef.current?.close();
// Enable/disable items
menuRef.current?.enableItems(['Delete', 'Archive'], false);
// Show/hide items
menuRef.current?.showItems(['Delete']);
menuRef.current?.hideItems(['Export']);
// Add items
menuRef.current?.insertAfter(
[{ text: 'New Option' }],
'Existing Item'
);
// Remove items
menuRef.current?.removeItems(['Outdated Item']);
// Get item index
const indices = menuRef.current?.getItemIndex('Copy');
次のステップ: 必要に応じてリファレンスを選択してください。getting-started.md から始めるか、他のリファレンスで特定の機能をご確認ください。