简体   繁体   English

无法在 ipcRenderer 的反应组件中导入 electron

[英]cannot import electron in react componment for ipcRenderer

So I am trying to import the ipcRenderer into a react component to communicate with the electron side.所以我试图将 ipcRenderer 导入到反应组件中以与 electron 端进行通信。 The issue is I cannot import electron. I tried问题是我无法导入 electron。我试过了

import { ipcRenderer } from 'electron/renderer'

returns module electron/renderer not found未找到返回模块电子/渲染器

import { ipcRenderer } from 'electron'

returns fs.existsSync is not a function返回 fs.existsSync 不是 function

const renderer = require('electron');

returns fs.existsSync is not a function返回 fs.existsSync 不是 function

const renderer = require('electron').ipcRenderer;

returns fs.existsSync is not a function返回 fs.existsSync 不是 function

const renderer = window.require('electron');

returns window.require is not a function返回 window.require 不是 function

I do not know what to do anymore, I have tried everything我不知道该怎么办了,我已经尝试了一切

I got it!我知道了! using electron-react-bolierplate they prepared a custom preload.js script that exposes three functions to the rendered components: myPing : (Just a demo, send a ping message to the console) and exposes the on and once ipcRenderer methods他们使用electron-react-bolierplate准备了一个自定义的preload.js脚本,该脚本向渲染的组件公开了三个函数: myPing :(只是一个演示,向控制台发送 ping 消息)并公开了ononce ipcRenderer 方法

import { Component } from 'react';
...
...
    class Hello extends Component {
      componentDidMount() {
        console.log('Mounted!', 'Window', window, 'electronApi', window.electron, 'ipcRenderer', window.electron.ipcRenderer);
    
        window.electron.ipcRenderer.on('ipc-example', (arg) => {
          // eslint-disable-next-line no-console
          console.log(arg);
        });
    
        window.electron.ipcRenderer.myPing();
      }
    
      render() {
        return (
          <div>
    ...
    ...

I used to have same problem.我曾经有同样的问题。 You should not import electron directly inside your renderer/react component.您不应该直接在渲染器/反应组件中导入 electron。 Instead in your preload.ts file you are given some basic configuration by electron-react-bolierplate to use.相反,在您的 preload.ts 文件中,您可以使用 electron-react-bolierplate 的一些基本配置。

So inside your react component you should use window.electron.ipcRenderer.on('channel-name', args) sample below所以在你的反应组件中,你应该使用window.electron.ipcRenderer.on('channel-name', args)示例

 const myEventHandler = () => { window.electron.ipcRenderer.on('channel-name', (event, data) => { console.log('data, event', data, event); }); };

window.electron, here electron is the name given in preload.ts file. window.electron,这里的electron是preload.ts文件中给的名字。 contextBridge.exposeInMainWorld('electron', {...})

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM