使用 Electron 从 React 组件打开文件对话框

use*_*848 1 reactjs electron

所以我知道无需对渲染线程做出反应,我就可以打开文件对话框。

const {dialog} = require('electron').remote
dialog.showOpenDialog({properties: ['openFile']}))
Run Code Online (Sandbox Code Playgroud)

不过,我正在尝试使用 React 并学习 React 和 Electron 的工作流程。执行要求会给我以下错误。

TypeError: fs.existsSync is not a function
getElectronPath
   5 | var pathFile = path.join(__dirname, 'path.txt');
   6 | 
   7 | function getElectronPath() {
>  8 |   if (fs.existsSync(pathFile)) {
   9 |     var executablePath = fs.readFileSync(pathFile, 'utf-8');
  10 | 
  11 |     if (process.env.ELECTRON_OVERRIDE_DIST_PATH) {
View compiled
(anonymous function)
  18 |   }
  19 | }
  20 | 
> 21 | module.exports = getElectronPath();
View compiled
Run Code Online (Sandbox Code Playgroud)

不确定我能做些什么来完成这项工作。应该是一个非常简单的画布绘图应用程序,但我确实需要枚举文件夹中的图像并为应用程序提供文件对话框功能。任何想法如何解决这个问题?

use*_*848 5

我找到了解决方案。您可以在创建时将 preload.js 运行到窗口中,然后调用 javascript 对象等项目。

在 github https://github.com/electron/electron/issues/9920上发现了这个问题

  mainWindow = new BrowserWindow({
    width: 800, 
    height: 600,
    webPreferences: {
      nodeIntegration: false,
      preload: __dirname + '/preload.js'
    }
  });
Run Code Online (Sandbox Code Playgroud)

预加载.js

const { dialog } = require('electron').remote;
window.electron = {};
window.electron.dialog = dialog;
Run Code Online (Sandbox Code Playgroud)

然后我想加载到窗口中的任何内容我都可以添加到 window.electron 对象并毫无问题地调用它。React 预编译器比电子更重要。