弹出窗口中的React以何种方式与父窗口通信?

ffx*_*sam 8 reactjs

我有一个OAuth进程弹出一个窗口,但是当我登录时,重定向到OAuth回调页面发生在弹出窗口而不是父窗口(window.opener).这可能有点hacky,但我想让弹出窗口告诉父母"我们被授权!".

这实际上有效:

OAuthCallback = React.createClass({
  displayName: 'OAuthCallback',

  render() {
    window.opener.console.log('hello parent window');

    return (
      <div>
        Hi, OAuth is process is done.
      </div>
    )
  }
});
Run Code Online (Sandbox Code Playgroud)

但我想知道是否有某种方法可以让弹出窗口告诉父窗口调用prop函数,例如this.props.oauthSucceeded().

Eel*_*lke 14

当您无法在组件之间建立任何父子关系或兄弟关系时,React建议您设置一个事件系统.

对于没有父子关系的两个组件之间的通信,您可以设置自己的全局事件系统.订阅componentDidMount()中的事件,取消订阅componentWillUnmount(),并在收到事件时调用setState().通量模式是安排这种方式的可能方式之一.

请参阅https://facebook.github.io/react/tips/communicate-between-components.html

看看window.postMessage跨窗口通信(https://developer.mozilla.org/en-US/docs/Web/API/Window/postMessage)


小智 5

Eelke的建议是正确的。

window.postMessage()在子窗口中使用,然后在main / master组件的方法中window.close()添加了一个。window.addEventListener('message', function(){})componentDidMount

查看https://facebook.github.io/react/tips/dom-event-listeners.html了解更多信息!