最小的例子:从反应应用中打开电子窗口? [英] Minimal Example: Opening a window in electron from react application?

查看:44
本文介绍了最小的例子:从反应应用中打开电子窗口?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

说我正在用react / redux& amp;构建桌面应用程序电子。因此,我在电子中的index.html文件如下所示:

Say I am building a desktop application with react/redux & electron. So my index.html file in electron looks like this:

<!DOCTYPE html>
<html>
 ...
  <body>

    <div id="content"></div>

  <script src="public/js/bundle.js"></script>
  </body>
</html>

我最大的React容器(称为app.js)被加载到'id = content'div中。到目前为止,这种方法工作正常,但是现在我想知道当用户单击我的应用程序中的按钮时如何打开一个新的文件对话框窗口(或任何与此相关的新窗口)。

My biggest React container (call it app.js) is loaded into the 'id=content' div. This works fine so far, but now I am wondering how to open a new file dialog window (or any new window for that matter) when the user clicks a button in my react application.

我在此处找到了一些示例此处,但是这两个示例仅说明了如何从主要电子过程(在渲染器或main中)加载文件对话框窗口。

I found some examples here & here, but both examples only explain how to load the file dialog window from the main electron processes (in renderer or main).

但是,我希望用户使用我的React应用程序,然后,一旦他或她单击一个按钮,我的应用程序应该告诉电子生成一个新窗口,当然,这个新窗口应该以某种方式成为我的react应用程序的一部分。

However, I want the user to engage with my React Application and then, once he or she clicks a button, my app should then tell electron to spawn a new window, and this new window should, of course, somehow be part of my react application.

如果有人可以在这里提供一个最小的示例,我将非常感激。

I would really appreciate it if someone could provide a minimal example here, on how these to things work together.

推荐答案

react 16中的 createPortal api将为您提供帮助。

The "createPortal" api in react 16 will help you.

首先,我们有一个这样的组件:

First let's say we have a component like this:

<SubWindow>
  <h1>bar</h1>
</SubWindow>

然后在其生命周期方法中打开(或关闭)一个窗口,如下所示:

Then open(or close) a window in its lifecycle methods like this:

export class SubWindow extends React.Component {
  nativeWindowObject: null;

  componentWillMount() {
    this.nativeWindowObject = window.open('');
  }
  render() {
    return this.nativeWindowObject ? ReactDOM.createPortal(this.props.children, this.nativeWindowObject.document.body) : null;
  }
}

注意:您必须设置webPreferences:{nativeWindowOpen:true },以确保 window.open返回一个本机Window对象。访问 https://electronjs.org/docs/api/window-open 了解更多信息

Notice: You MUST set webPreferences:{nativeWindowOpen: true} in your main window to make sure "window.open" returns a native Window object. Visit https://electronjs.org/docs/api/window-open for more infomation.

这篇关于最小的例子:从反应应用中打开电子窗口?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆