|
| 1 | +# useKeyCombination |
| 2 | + |
| 3 | +## Introduce |
| 4 | + |
| 5 | +지정된 키 조합을 눌렀을 때 콜백 함수를 호출하는 훅입니다. |
| 6 | + |
| 7 | +- 지정된 키들을 모두 눌렀을 때 콜백 함수를 호출하며, 필요에 따라 기본 동작을 막을 수도 있습니다. |
| 8 | +- 예를 들어, `Ctrl + K` 키 조합을 감지하여 특정 작업을 실행하고자 할 때 사용할 수 있습니다. |
| 9 | + |
| 10 | +```ts |
| 11 | +interface UseKeyCombinationProps { |
| 12 | + shortcutKeys: string[]; |
| 13 | + callback: () => void; |
| 14 | + isPrevent?: boolean; |
| 15 | +} |
| 16 | + |
| 17 | +const useKeyCombination = ({ |
| 18 | + shortcutKeys, |
| 19 | + callback, |
| 20 | + isPrevent = false, |
| 21 | +}: UseKeyCombinationProps): void |
| 22 | +``` |
| 23 | + |
| 24 | +### Props |
| 25 | + |
| 26 | +- `shortcutKeys` : 키 조합을 나타내는 키 코드의 배열 |
| 27 | +- `callback` : 키 조합이 감지되었을 때 실행할 콜백 함수 |
| 28 | +- `isPrevent` : true로 설정하면 키 조합이 눌렸을 때 기본 동작 방지 (기본값: false) |
| 29 | + |
| 30 | +## Examples |
| 31 | + |
| 32 | +```tsx copy filename="TestComponent.tsx" |
| 33 | +import { useCallback, useRef, useState } from 'react'; |
| 34 | +import useKeyCombination from './hooks/useKeyCombination'; |
| 35 | + |
| 36 | +function TestComponent() { |
| 37 | + const [bold, setBold] = useState(false); |
| 38 | + const [isSave, setIsSave] = useState(false); |
| 39 | + const input = useRef<HTMLInputElement>(null); |
| 40 | + |
| 41 | + const keyActions = { |
| 42 | + toggleBold: { |
| 43 | + shortcutKeys: ['ControlLeft', 'KeyB'], |
| 44 | + callback: useCallback(() => { |
| 45 | + setBold((state) => !state); |
| 46 | + }, [setBold]), |
| 47 | + }, |
| 48 | + save: { |
| 49 | + shortcutKeys: ['MetaLeft', 'KeyS'], |
| 50 | + callback: useCallback(() => setIsSave((state) => !state), [setIsSave]), |
| 51 | + isPrevent: true, |
| 52 | + }, |
| 53 | + search: { |
| 54 | + shortcutKeys: ['MetaLeft', 'KeyK'], |
| 55 | + callback: useCallback(() => input.current?.focus(), []), |
| 56 | + }, |
| 57 | + }; |
| 58 | + |
| 59 | + useKeyCombination(keyActions.toggleBold); |
| 60 | + useKeyCombination(keyActions.save); |
| 61 | + useKeyCombination(keyActions.search); |
| 62 | + |
| 63 | + return ( |
| 64 | + <div> |
| 65 | + <input type="text" ref={input} placeholder="Press command + K" /> |
| 66 | + <div>USE-REACT-HOOKS</div> |
| 67 | + <ul> |
| 68 | + <li style={{ fontWeight: bold ? 'bold' : 'normal' }}> |
| 69 | + command + B : Bold |
| 70 | + </li> |
| 71 | + <li>command + S: {isSave ? 'SAVE!' : 'Not saved yet'}</li> |
| 72 | + </ul> |
| 73 | + </div> |
| 74 | + ); |
| 75 | +} |
| 76 | +``` |
0 commit comments