les*_*ode 8 javascript postmessage reactjs
我正在尝试将 react url 作为 iframe 加载到我的 jsp 项目中。
这是我的发送方代码块:
<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', '*');
}
Run Code Online (Sandbox Code Playgroud)
我还尝试了以下方法:
function loadReactIframe(){
document.getElementById("eda").contentWindow.postMessage(
'GET MESSAGE FROM ME',
'http://myhost', 3000
);
}
Run Code Online (Sandbox Code Playgroud)
我的接收器(反应)代码块:
componentDidMount() {
window.addEventListener('load', this.handleLoad);
alert('componentDidMount')
}
handleLoad(event) {
alert(event.data);
}
Run Code Online (Sandbox Code Playgroud)
但我无法从事件中获取数据。
已经有一个为此制作的有用的钩子。https://www.npmjs.com/package/@rottitime/react-hook-message-event
自述文件页面有说明,但这里是它如何工作的想法安装挂钩:
npm i @rottitime/react-hook-message-event
Run Code Online (Sandbox Code Playgroud)
在您的组件中使用它就像使用任何其他钩子一样,例如useState.
将文件导入到您的组件中
npm i @rottitime/react-hook-message-event
Run Code Online (Sandbox Code Playgroud)
您可以收听消息并使用回调来响应。例如,采用以下场景:
hello父窗口监听子窗口的消息hello从孩子那里收到world给孩子import {useMessage} from '@rottitime/react-hook-message-event'
Run Code Online (Sandbox Code Playgroud)