electron 如何发送数据从电子到一个React组件在渲染页面?

w8ntj3qf  于 2022-12-25  发布在  Electron
关注(0)|答案(1)|浏览(270)

post解释了如何使用mainWindow.webContents.sendfunction来将数据"提交表单"从电子发送到使用.html和JavaScript绘制的页面"内部"。
问题是:这在React中无法工作。我的应用甚至无法将ipcRendererelectron识别为app.tsx(主根组件)内部的东西。
https://www.electronjs.org/docs/latest/api/web-contents#contentssendchannel-args
服务器端:

const mainWindow = createWindow('main', {
    width: 1920,
    height: 1080,
    minWidth: 1366,
    minHeight: 768,
    webPreferences: {
      nodeIntegration: true
    }
  })

if (isProd) {
    await mainWindow.loadURL('app://./home.html')
} else {
    const port = process.argv[2]
    await mainWindow.loadURL(`http://localhost:${port}/home`)
    mainWindow.webContents.openDevTools()
}

mainWindow.webContents.on('did-finish-load', () => {
   mainWindow.webContents.send('submitted-form', "hello")
})

app.tsx:

// error since electron is not available within app.tsx
// electron requires 'fs' modules which client-side doesn't have
const { ipcRenderer } = require("electron")

class _app extends React.Component<any, any> {
  constructor(props: any) {
    super(props)
  }

 componentDidMount() {
    ipcRenderer.on("submitted-form", function (event, data) {
      console.log("received data", data)
    })
  }
}
wmomyfyw

wmomyfyw1#

以防你没能挺过来。
我在主渲染器和渲染器之间传递信息的方式如下:
对于main.js(主电子过程)

const { app, BrowserWindow, ipcMain } = require('electron');
const path = require('path');

const ProductService = require('./services/product.service');

const productService = new ProductService();

/*This "service" is some "promise" data from sequelize, just keep in mind 
the data here is a promise*/
async function getProducts() {
  const products = await productService.getAllProducts();
  return products
}

function mainWindow() {
    const mainWin = new BrowserWindow({
        width: 1000,
        height: 800,
        webPreferences: {
          preload: path.join(__dirname, 'preload.js')
        }
    })

    mainWin.loadFile('./public/index.html');
    mainWin.loadURL('http://localhost:3000')
}

app.whenReady().then(() => {
    /* Here is where you send the message which you have to recive from 
       your preload file, the first arg is the name by which you will 
       identify it and the second is the message itself */
    ipcMain.handle('products', getProducts);
    mainWindow()
    app.on('activate', function () {
      if (BrowserWindow.getAllWindows().length === 0) mainWindow()
    })
  })

在预加载文件中,您应该会收到如下所示的文件:

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

contextBridge.exposeInMainWorld('Products', {
    products: () => ipcRenderer.invoke('products').then(result => result)
})

在组件的末尾,您希望呈现接收信息所需的信息,如下所示:

React.useEffect(() => {
        /* These are the names that you into the preload file */
        window.Products.products()
        .then(result => {
            setRows(result)})
}, [])

相关问题