微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

electron+react 进程间通信碰见的问题解决

在写主进程和react组件(渲染进程)间通讯时,碰见了很多的问题,主要如下

  • TypeError:fs.existsSync is not a function
  • Cannot destructure property ‘ipcRenderer’ of ‘window.electron’ as it is undefined.
  • electron react window.require is not a function
    上述三个问题,主要是主进程和raect组件间通信的问题。解决方法如下:
  1. main.js中
var electron = require('electron');
const {ipcMain} = require('electron')
var app = electron.app;     //引用app
var browserWindow = electron.browserWindow;   //窗口引用

var mainWindow = null;    //声明要打开的主窗口

app.on('ready',()=>{
    mainWindow = new browserWindow(
        {
            width:800,
            height:800,
            webPreferences:{
                nodeIntegration: true,   //改认设置  在主进程中设置,允许使用node语法
             },
        });
    ipcMain.on('editfile',(event,arg)=>{
        console.log(arg);
    })
    mainWindow.loadURL('http://localhost:3000/');mainWindow.loadFile(path.join(__dirname,'./public/index.html'))
    // 关闭窗口时将主窗口设置为null
    mainWindow.on('closed',()=>{
        mainWindow = null;
    })
})

主要是设置webPreferences中的nodeIntegration: true
2.index.html中
在public目录下找到index.html,在index.html中添加下面代码

    <script>global.electron = require('electron')</script>

<body></body>里面 root之前, 具体如下所示

<body>
    <noscript>You need to enable JavaScript to run this app.</noscript>
    <script>global.electron = require('electron')</script>
    <div id="root"></div>
  </body>

这个时候主进程中有了ipcMain ,也允许node语法的情况下
3.需要加ipcRenderer的react组件(渲染进程)中
引用下面的代码

const electron = window.electron;

这时候需要注意的是, 这时候的引入不是在import React
from ‘react’后面跟,而是写在组件中。例如下面EditFile函数组件

import React from 'react'

export default function EditFile() {
    const electron = window.electron;   //在这里进行引入
    const minWindow = (e)=>{
        e.preventDefault()
        electron.ipcRenderer.send("editfile","pong")
    }
    return (
        <div>
            <h1 onClick={(e)=>minWindow(e)}>editfile</h1>
        </div>
    )
}

这时候去启动react的话,就可以在控制台得到ipcRenderer发来的信息

在这里插入图片描述

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 [email protected] 举报,一经查实,本站将立刻删除。

相关推荐