how to communicate between react and electron

后端 未结 1 1110
野的像风
野的像风 2020-12-11 09:34

Creating desktop application using react and electron.I want to call method in main.js of electron from react component.In angular there was a npm package.

i         


        
相关标签:
1条回答
  • 2020-12-11 09:48

    At your Renderer.js

    const { ipcRenderer } = require('electron');
    
    async function runCommand(cmd) {
      const res = await ipcRenderer.sendSync('runCommand', cmd);
      return res;
    }
    

    At you main.js

    // Listen event through runCommand channel
    // And return the result to Renderer.
    ipcMain.on('runCommand', async (event, arg) => {
      event.returnValue = await runCommand(arg);
    });
    

    This is the simplest way to communicate between main and renderer process.

    But I think you are going to send the result from the main process to renderer using mainWindow.webContents.send('return-exe', '');

    So this means, you are sending the result through return-exe IPC channel from main to renderer. And you should listen event from this channel at your renderer. Like this

    ipcRenderer.on('retrun-exe', (event, arg) => {
        ...
    });
    

    You can add this listener at your lifecycle functions. I was used to add this to componentDidMount() But in your case, please add this to your useEffect()

    0 讨论(0)
提交回复
热议问题