【问题标题】:Returning result from Electron to React从 Electron 返回结果到 React
【发布时间】:2021-01-04 12:56:57
【问题描述】:

我有一个电子方法可以打印:

ipcMain.on('print', (results, total) => {
    PosPrinter.print(print_data, {
      printerName: 'RECEIPT',
      preview: false,
      width: '170px',               //  width of content body
      margin: '15 15 15 15',            // margin of content body
      copies: 1,                   
      silent : true
  })
  .then(() => {
    // some code ...
    console.log("done");
    return "Printing successful.."
  })
  .catch((error) => {
    console.error(error);
    return "Something went wrong."
});

我正在响应端访问此方法,例如:

  handlePrint = (e) => {
    e.preventDefault();
    ipcRenderer.send('print', this.state.cheques, this.state.total);
  }

如果打印成功或渲染器出错,我如何返回状态消息?

【问题讨论】:

    标签: reactjs electron


    【解决方案1】:

    您必须使用 ipcMain.on()

    中的 event.reply() 函数

    以您的代码为例。

    主进程。 电子

    ipcMain.on('print', (event, results, total) => {
    // some code
    
    .then(() => {
     // some code ...
     event.reply('print', 'Printing successful..')
    
    }).catch((error) => {
     event.reply('print', 'Something went wrong.')
    });
    

    渲染器进程(网页)。 React

    ipcRenderer.on('print', (event, arg) => {
      console.log(arg) // prints "Printing successful.." or "Something went wrong."
    })
    

    您可以在组件或 App.js 的 componentDidMount()useEffect() 中分配渲染过程代码

    这是在执行时将数据从主进程传输到渲染进程作为返回函数的方式。

    https://www.electronjs.org/docs/api/ipc-main#sending-messages

    【讨论】:

      猜你喜欢
      • 2017-01-23
      • 1970-01-01
      • 2021-11-10
      • 1970-01-01
      • 1970-01-01
      • 2018-11-08
      • 2012-12-19
      • 2019-09-03
      • 2016-09-03
      相关资源
      最近更新 更多