問題のコード
以下のコードでは、onKeyDownイベントが発火しません。
const startAction = (e: any) => {
if (e.key === 'Enter' || e.key === ' ') console.log('hello');
};
return (
<div
className='h-screen w-full flex items-center justify-center'
onKeyDown={startAction}
>
スペースかEnterを押してね!
</div>
);
これではeventが起こりませんでした。
原因
以下の2点が原因です
-
KeyboardEventはフォーカスを持つ要素でのみ発火する -
div要素はフォーカスを持たない
Interactive elements must be focusable
If the user can interact with an element (for example, using touch or a pointing device),
then it should be focusable using the keyboard. You can make it focusable by adding a
tabindex=0attribute value to it.
That will add the element to the list of elements that can be focused by pressing the Tab key,
in the sequence of such elements as defined in the HTML document.
解決法
divにtabIndex属性を追加して、フォーカス可能にすることで解決できます。
HTMLの場合はtabindexですが、JSXの場合はtabIndexになります
それではtabIndexをdivに追加します。以下は修正後のコードです
const startAction = (e: any) => {
if (e.key === 'Enter' || e.key === ' ') console.log('hello');
};
return (
<div
tabIndex={0}
className='h-screen w-full flex items-center justify-center'
onKeyDown={startAction}
>
スペースかEnterを押してね!
</div>
);
結果↓
hello