如何将 React 点击事件传递给电子

分享于2022年07月17日 electron javascript node.js reactjs 问答
【问题标题】:如何将 React 点击事件传递给电子(How to pass React click events to electron)
【发布时间】:2022-01-05 22:59:55
【问题描述】:

刚刚下载 electron-react-boilerplate 并开始使用样板,但是当我尝试创建一个无装饰的透明窗口时出现问题,所以我创建了一个小的 React TitleBar 组件,但我不知道如何发送widnow最小化、最大化和关闭命令。我知道必须使用 ipcRenderer 完成某种工作,但我什至无法将其导入到我的 React 组件中

至于测试,下载了 electron-react-boilerplate 4.4.0 并尝试在 React App 组件中导入 ipcRenderer,这是我的 React 组件的结果代码,我附上了我在控制台中得到的错误.

import { Component } from 'react';
import { ipcRenderer } from 'electron';

import { MemoryRouter as Router, Switch, Route } from 'react-router-dom';

import icon from '../../assets/icon.svg';
import './App.css';

class Hello extends Component {
  componentDidMount() {
    console.log(ipcRenderer);
  }

  render() {
    return (
      
icon

electron-react-boilerplate

); }; } export default function App() { return ( ); }
ERROR in ./node_modules/electron/index.js 1:11-24
Module not found: Error: Can't resolve 'fs' in '/home/martinb/Escritorio/electron-react-boilerplate-4.4.0/node_modules/electron'
 @ ./src/renderer/App.tsx 10:19-38
 @ ./src/renderer/index.tsx 10:30-46

ERROR in ./node_modules/electron/index.js 2:13-28
Module not found: Error: Can't resolve 'path' in '/home/martinb/Escritorio/electron-react-boilerplate-4.4.0/node_modules/electron'

BREAKING CHANGE: webpack < 5 used to include polyfills for node.js core modules by default.
This is no longer the case. Verify if you need this module and configure a polyfill for it.

If you want to include a polyfill, you need to:
        - add a fallback 'resolve.fallback: { "path": require.resolve("path-browserify") }'
        - install 'path-browserify'
If you don't want to include a polyfill, you can use an empty module like this:
        resolve.fallback: { "path": false }
 @ ./src/renderer/App.tsx 10:19-38
 @ ./src/renderer/index.tsx 10:30-46

webpack compiled with 2 errors
Not rewriting GET /index.html because the path includes a dot (.) character.


【解决方案1】:

你可以在反应组件中使用 window.electron.ipcRenderer

preload.js 中应该需要ipcRenderer,preload 是BrowserWindow webPreferences 的一个参数。

  mainWindow = new BrowserWindow({
    show: false,
    width: 1024,
    height: 728,
    icon: getAssetPath('icon.png'),
    webPreferences: {
      preload: path.join(__dirname, 'preload.js'),
    },
  });

请参考: https://github.com/electron-react-boilerplate/electron-react-boilerplate/blob/main/src/main/main.ts

  • 我猜,他们为什么不直接在 react App 组件的 componentDidMount 中包含调用...谢谢您的回答!