JSFiddle - React, Tailwind, and code Playground
by 규연 황
HTML
key
JavaScript
// Using a switch statement can be verbose
const handleKeyDown = () => {
console.log('eee')
/* switch (key) {
case 'Escape':
endGame();
break;
case 'ArrowUp':
moveUp();
break;
case 'ArrowLeft':
moveLeft();
break;
case 'ArrowDown':
moveDown();
break;
case 'ArrowRight':
moveRight();
break;
} */
}
// Achieve the same this in a more graceful way using an object
c/* onst moves = {
Escape: endGame,
ArrowUp: moveUp,
ArrowLeft: moveLeft,
ArrowDown: moveDown,
ArrowRight: moveRight,
};
const handleKeyDown = ({ key }) => {
if (moves[key]) {
moves[key]();
}
} */
document.addEventListener('keydown', handleKeyDown)