【问题标题】:electron-react-boilerplate: window.electron does not exist Error电子反应样板:window.electron 不存在错误
【发布时间】:2021-11-26 02:02:50
【问题描述】:

我正在使用电子反应样板 v4.0.0 我已经从 preload.js 中公开了这个电子 API,以便在渲染器进程中使用。 preload.js

在反应组件中尝试使用“window.electron.ipcRenderer.printTicket()”时会出现问题。

Hello React Component

我有错误:“window.electron 不存在于类型 'Window & typeof globalThis'”。

【问题讨论】:

  • 欢迎来到 Stack Overflow!您能否将您的代码发布为文本而不是屏幕截图?

标签: electron electron-react-boilerplate


【解决方案1】:

@丹尼尔,

试试这个:-

通过以下方式编辑您的 index.tsx:-

import { render } from "react-dom";
import App from "./App";


render(<App />, document.getElementById("root"));

到这样的事情:-

import { render } from "react-dom";
import App from "./App";

declare global {
  interface Window {
    electron: any;
  }
}

render(<App />, document.getElementById("root"));

现在您可以在渲染器中的任何位置使用 window.electron。这解决了我的问题。您也可以在 App.js 文件中添加它。

虽然我没有测试过,但你也可以这样做:-

preload.js

const { contextBridge, ipcRenderer } = require('electron');

contextBridge.exposeInMainWorld('electron', {
  hworld: "Hello world" // window.electron.hworld is a string ("Hello world")
});

index.tsx

import { render } from "react-dom";
import App from "./App";

declare global {
  interface Window {
    electron: {
      hworld: string // Since you know window.electron.hworld is a string
    }
  }
}

render(<App />, document.getElementById("root"));

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-09-29
    • 1970-01-01
    • 2021-12-24
    • 2017-04-28
    • 2021-01-22
    • 2021-12-11
    • 2019-10-04
    • 2017-12-29
    相关资源
    最近更新 更多