【问题标题】:How can i get postmessage data from react?我如何从反应中获取消息后数据?
【发布时间】:2019-08-20 01:13:13
【问题描述】:

我正在尝试在我的 jsp 项目中将 react url 作为 iframe 加载。

这里是我的发送方代码块:

<iframe id="eda" 
               style="display: none;"
                src="http://myhost:3000/"
                width="100%" height="600" border="0" marginwidth="0"
                marginheight="0" scrolling="no">
</iframe>   

****

function loadReactIframe(){
    document.getElementById("eda").contentWindow.postMessage('GET MESSAGE FROM ME', '*');
}

我还尝试了以下方法:

function loadReactIframe(){
      document.getElementById("eda").contentWindow.postMessage(
            'GET MESSAGE FROM ME', 
            'http://myhost', 3000
     );
}

我的接收器(react)代码块:

componentDidMount() {
     window.addEventListener('load', this.handleLoad);
     alert('componentDidMount')
}

handleLoad(event) {
     alert(event.data);
}

但我无法从事件中获取数据。

【问题讨论】:

  • 试试这个...window.addEventListener('message', function(event){ });
  • 消息事件无法捕获发布消息。 ://
  • 你的接收者在iframe里面,对吧??
  • 是的,我的接收器是一个 react 项目,我从 iframe 中的一个 jsp 项目中调用它。
  • 监听初始化后是否调用loadReactIframe...

标签: javascript reactjs postmessage


【解决方案1】:

已经为此制作了一个有用的钩子。 https://www.npmjs.com/package/@rottitime/react-hook-message-event

自述文件页面有说明,但这里是它的工作原理 安装挂钩:

npm i @rottitime/react-hook-message-event

在您的组件中使用它,就像使用任何其他钩子一样,例如useState.

在你的组件中导入文件

import {useMessage} from '@rottitime/react-hook-message-event'

您可以收听消息并使用回调进行响应。比如下面的场景:

  1. 父窗口从子窗口监听消息hello
  2. 家长从孩子那里收到hello
  3. 家长将world 发回给孩子
//listens for the 'hello' message from window.postMessage()
useMessage('hello', (send, payload) => {
  //use sendMessage to post back to the sender
  send({ type: 'world', success: true });
});

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-06-21
    • 2019-10-27
    • 1970-01-01
    • 2019-10-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多