問題のコード
以下のコードでは、onKeyDown
イベントが発火しません。
qiita.rb
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=0
attribute 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
に追加します。以下は修正後のコードです
qiita.rb
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>
);
結果↓
qiita.rb
hello