如何将箭头键绑定添加到 react\redux

How to add arrow keybinding to react\redux

最后我创建了一个游戏,它是一个 3 个答案的问答游戏,但我希望能够使用向上和向下键滚动浏览 3 个答案,它们是 3 个按钮。但我一直在为如何实现它而苦苦挣扎,以前有人试过吗?或任何提示?

这是我要添加到我的 redux 中的虚拟代码,但它不是很实用

<!DOCTYPE html>
<html>

<head>
  <style>
    a:focus, a:active {
    font-size: 18px;
    color: red;
    font-family: Helvetica;
    }

   .btn:focus {
     background: green;
     outline: none;
   }
</style>
</head>

<body onkeydown="myFunction(event)">

  <a id="myAnchor" href="https://www.w3schools.com">Visit W3Schools.com</a>

  <p id="demo"></p>

  <input class="btn" id="btn-1" type="button"  value="First dog">
  <input class="btn" id="btn-2" type="button"  value="Second dog">
  <input class="btn" id="btn-3" type="button"  value="Third dog">

  <script>
    window.onload = () => {
      document.getElementById("btn-1").focus();
      console.log(document.activeElement)
    };

    function myFunction(event) {
      const btn1 = document.getElementById("btn-1");
      const btn2 = document.getElementById("btn-2");
      const btn3 = document.getElementById("btn-3");

      const keyPress = event.which || event.keyCode;
      const focusedButtonElement = document.activeElement.id

      switch(focusedButtonElement) {
        case "btn-1":
          if (keyPress === 39) return btn2.focus() 
        case "btn-2":
          if (keyPress === 37) return btn1.focus() 
          if (keyPress === 39) return btn3.focus() 
        case "btn-3":
          if (keyPress === 37) return btn2.focus() 
        default:
        break
      }

      if(keyPress === 13) {
        document.activeElement.click();
        console.log("clicked")
      }

    }
  </script>

</body>

</html>

谢谢大家

从 body 标记中删除 onkeydown 事件侦听器,并修改 window.onload 函数以编程方式添加事件侦听器。

window.onload = () => {
    document.getElementById("btn-1").focus();
    console.log(document.activeElement)
    document.addEventListener('keydown');
};