---
title: 快捷鍵
image: /images/user-guide/table-views/table.png
---
## 介紹
當您需要監聽快捷鍵時,通常會使用 `onKeyDown` 事件監聽器。
然而,在 `twenty-front` 中,您可能會遇到在不同組件中使用相同快捷鍵的衝突,且這些組件同時加載。
例如,如果您有一個頁面在監聽 Enter 鍵,而一個模態框也在監聽 Enter 鍵,而該模態框內部還有一個 Select 組件在監聽 Enter 鍵,那麼當所有這些組件同時加載時,您可能會遇到衝突。
## `useScopedHotkeys` 鉤子
為了解決這個問題,我們提供了一個自定義鉤子,使其能夠在沒有任何衝突的情況下聽取快捷鍵。
您可以將其放在組件之中,該鉤子將只在組件加載並且指定的 **快捷鍵作用域** 啟用時監聽快捷鍵。
## 實際上如何監聽快捷鍵?
設置快捷鍵監聽涉及兩個步驟:
1. 設置將監聽快捷鍵的[快捷鍵作用域](#what-is-a-hotkey-scope-)
2. 使用 `useScopedHotkeys` 鉤子來監聽快捷鍵
即使在簡單頁面中也必須設置快捷鍵作用域,因為其他用戶界面元素如左側菜單或指令菜單也可能會聽取快捷鍵。
## 快捷鍵的用例
一般來說,您將有兩種需要快捷鍵的用例:
1. 頁面內或加載在頁面中的組件
2. 因用戶操作而獲得焦點的模態框組件
第二個用例可以遞歸發生:例如在模態框中的下拉框。
### 在頁面中監聽快捷鍵
示例:
```tsx
const PageListeningEnter = () => {
const {
setHotkeyScopeAndMemorizePreviousScope,
goBackToPreviousHotkeyScope,
} = usePreviousHotkeyScope();
// 1. Set the hotkey scope in a useEffect
useEffect(() => {
setHotkeyScopeAndMemorizePreviousScope(
ExampleHotkeyScopes.ExampleEnterPage,
);
// Revert to the previous hotkey scope when the component is unmounted
return () => {
goBackToPreviousHotkeyScope();
};
}, [goBackToPreviousHotkeyScope, setHotkeyScopeAndMemorizePreviousScope]);
// 2. Use the useScopedHotkeys hook
useScopedHotkeys(
Key.Enter,
() => {
// Some logic executed on this page when the user presses Enter
// ...
},
ExampleHotkeyScopes.ExampleEnterPage,
);
return
My page that listens for Enter
;
};
```
### 在模態框型組件中監聽快捷鍵
在此示例中,我們將使用一個監聽 Escape 鍵的模態組件來告知其父組件關閉它。
這裡用戶交互會更改範圍。
```tsx
const ExamplePageWithModal = () => {
const [showModal, setShowModal] = useState(false);
const {
setHotkeyScopeAndMemorizePreviousScope,
goBackToPreviousHotkeyScope,
} = usePreviousHotkeyScope();
const handleOpenModalClick = () => {
// 1. Set the hotkey scope when user opens the modal
setShowModal(true);
setHotkeyScopeAndMemorizePreviousScope(
ExampleHotkeyScopes.ExampleModal,
);
};
const handleModalClose = () => {
// 1. Revert to the previous hotkey scope when the modal is closed
setShowModal(false);
goBackToPreviousHotkeyScope();
};
return
My page with a modal
{showModal && }
;
};
```
然後在模態組件中:
```tsx
const MyDropdownComponent = ({ onClose }: { onClose: () => void }) => {
// 2. Use the useScopedHotkeys hook to listen for Escape.
// Note that escape is a common hotkey that could be used by many other components
// So it's important to use a hotkey scope to avoid conflicts
useScopedHotkeys(
Key.Escape,
() => {
onClose()
},
ExampleHotkeyScopes.ExampleModal,
);
return