用于 Web 键盘快捷键的 Electron React Native

Electron React Native for Web Keyboard Shortcuts

我正在尝试专门为 react-native-web 应用程序的电子(网络)构建添加键盘快捷键。

我确实有一些快捷方式已经在 index.electron.js 中定义为加速器,但我希望这些新快捷方式不存在于菜单中,它们需要反应 actions/reducers 才能执行。

我尝试将 window.onkeydown = (e) => { 添加到 App.web.js::componentDidMount 中,但这仅在 运行 在浏览器中打开应用程序时有效。当我构建应用程序并在 electron 中 运行 时(运行 文件的 .web 版本)我遇到关于 window 未定义的崩溃。

我对如何向使用 React-Native for web 构建的 Electron 应用程序添加键盘 shortcuts/event 侦听器(触发特定于反应的代码)感到困惑。

提前致谢

我不经常使用react-native,所以我不确定是否可以仅使用框架来做到这一点。 假设您使用的是 npm,您可以下载一个支持此功能的软件包。 react-hotkeys 听起来它可以完成您需要的快捷方式。

您应该使用 Electron API globalShortcut and IPC 将事件发送到网页。

主要流程代码

  const { globalShortcut } = require('electron')

  // this will be triggered when the accelerator is pressed
  // even if the app is in the background
  const ret = globalShortcut.register("Your_Accelerator", () => {
    yourWindow.webContents.send("shortcut", "shortcut has been pressed")
  });

  if (!ret) {
    console.log("registration failed");
  } else {
    console.log("registration succeeded");
  }

渲染器进程代码

  const { ipcRenderer } = require("electron");
  ipcRenderer.on("shortcut", (event, message) => {
    console.log(message) // Prints "shortcut has been pressed"
  })