如何将电子菜单数据发送到React组件?

问题描述 投票:0回答:1

在我的 React/Electronjs 项目中,这是我想要实现的目标:

  • 在电子js窗口的菜单方面,我想要一个使用电子对话框和fs包获取文件文本内容的函数,并且我希望将文本内容发送并显示到反应组件

我面临的问题:

  1. 我对 electrojs 相当陌生,我不完全理解如何将文件的文本内容数据发送到组件
  2. 我不知道如何正确渲染组件内的内容。
// main.js
const { app, BrowserWindow, dialog, Menu, ipcMain } = require('electron')
const fs = require('fs')
const os = require('node:os')
const path = require('node:path')
require('@electron/remote/main').initialize()
const isMac = process.platform === 'darwin'

function createWindow() {
  const win = new BrowserWindow({
    width: 800,
    height: 600,
    titleBarStyle: "default",
    webPreferences: {
      contextIsolation: true,
      nodeIntegration: false,
      preload: path.join(__dirname, 'preload.js')
    }
  })

  win.setRepresentedFilename(os.homedir())
  win.setDocumentEdited(true)
  win.loadURL('http://localhost:3000')

  const template = [
    ...(isMac
      ? [{
        label: app.name,
        submenu: [
          { role: 'about' },
          { type: 'separator' },
          { role: 'services' },
          { type: 'separator' },
          { role: 'hide' },
          { role: 'hideOthers' },
          { role: 'unhide' },
          { type: 'separator' },
          { role: 'quit' }
        ]
      }]
      : []),
    // { role: 'fileMenu' }
    {
      label: 'File',
      submenu: [
        {
          label: 'Open File',
          click: () => {

            const files = dialog.showOpenDialogSync(win,
              {
                properties: ['openFile'],
                filters: [{ name: "Text Files", extensions: ['txt'] }]
              }
            );
            // If no files 
            if (!files) return;


            const file = files[0];
            //const fileContent = fs.promises.readFile(file, 'utf-8');
            const fileContent = fs.readFileSync(file).toString();
            win.webContents.send('open-file', fileContent)
          }
        }

      ]
    }
  ]
  const menu = Menu.buildFromTemplate(template);
  Menu.setApplicationMenu(menu);
  return win
}

app.on('window-all-closed', function () {
  if (process.platform !== 'darwin') {
    app.quit()
  }
})

app.whenReady().then(() => {
  createWindow()
  app.on('activate', function () {
    if (BrowserWindow.getAllWindows().length === 0) {
      createWindow()
    }
  })
})
// preload.js 

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

contextBridge.exposeInMainWorld('electronAPI', {
  openFile: (callback) => ipcRenderer.on('open-file', (_event, content) => callback(content))
})
javascript reactjs electron
1个回答
0
投票

//预加载.js

const { contextBridge, ipcRenderer } = require('电子/渲染器');

contextBridge.exposeInMainWorld('电子API', { openFile: (回调) => ipcRenderer.on('打开文件', (_event, content) => 回调(内容)) })

© www.soinside.com 2019 - 2024. All rights reserved.