将Redux组件添加到iframe中的反应

问题描述:

我有React组件使用Redux Store。在componentDidMount中,此组件还应该将其他组件添加到iframe中。此iframe独立不在组件代码中创建。将Redux组件添加到iframe中的反应

<iframe src="empty.html"></iframe> 

componentDidMount(){ 
    let iframe = document.querySelector('iframe'); 
    let iframeBody = iframe.contentWindow.document.body; 
    let el = iframe.contentWindow.document.createElement('div'); 
    iframeBody.appendChild(el); 
    ReactDOM.render(<ReactRedux.Provider store={store}><SkCanvas /></ReactRedux.Provider>,iframeBody.querySelector('div')); 
    } 

此代码不会引发任何错误。在新组件SkCanvas中是带有道具的console.log,并且此日志显示在我的控制台中。只需html代码就可以在iframe中看到。 当然,如果我尝试将此组件添加到iframe之外的任何元素,它都可以工作。

任何提示如何添加它?

也可以手动将此组件设置为ifrmae(在i​​nit上),但我需要在这些组件之间共享存储。

在此先感谢您的任何提示。

+0

_此代码不会引发任何错误。在新的组件SkCanvas是console.log与道具和这个日志显示在我的控制台。只要html代码在iframe中可见即可。你能更精确吗?你想追加哪些组件? console.log的o/p是什么? – Dane

+0

''由其他组件附加到iframe中。在SkCanvas中是'console.log(道具)',这个日志是可见的。但是html在iframe中不可见。 通常只有一件事是我需要的是使用分离的CSS样式代码indise iframe和外部。 – jaroApp

+0

这是_other component_?这个'componentDidMount'属于哪个组件? – Dane

反应并不保留context横跨ReactDOM.render()。因此,store不会在iframe之外的组件之间共享,如果您使用2个独立的ReactDOM.render() s,组件之间也不会共享store
通常,如果要在任何HTML元素内渲染组件,则可以使用以下模式。

你的HTML元素:

<iframe id='iframe1'></iframe> 

然后js文件:

import React, { Component } from 'react'; 
import ReactDOM from 'react-dom'; 
import {Provider} from 'react-redux'; 

const store = configureStore(); 

class SkCanvas extends Component { 
    render() { 
    . 
    . 
    . 
    } 
} 

class FrameApp extends Component { 
    render() { 
    return (
     <Provider store={store}> 
     <SkCanvas/> 
     </Provider> 
    ); 
    } 
} 

ReactDOM.render(
    <FrameApp/>, 
    document.getElementById('iframe1') 
); 

编辑:为了使应用程序做出反应成和iframe,您可以使用​​。该库确保Redux存储在iframe中也可用。另请参见https://github.com/ryanseddon/react-frame-component/issues/29

+0

感谢您的回答。用你的例子。我需要在标准'div'中渲染''。 iframe中只有''。我可以使用'FrameApp''

some

'但它不起作用。 我的目标是:使用一个商店,我可以使用''。 'FrameApp'中嵌套元素的一部分应该放在iframe之外,另外一个''应该放在iframe里面,因为我需要将画布和CSS样式分开,而我用它来放置其他元素。 – jaroApp
+0

看到我更新的答案,并检查图书馆是否解决了问题 – Dane

+0

它看起来很有效。我需要检查商店是否也在父组件中更新,以便在iframe中进行操作,但现在它运行良好。谢谢。 – jaroApp