简体   繁体   English

在React应用程序内部,如何动态创建一个element(div)并在其中渲染一个React应用程序?

[英]Inside a react app, how can I dynamically create an element(div) and render a react app inside that?

I am building a chat application using react-redux. 我正在使用react-redux构建聊天应用程序。 This chat application will take multiple interactions at a time and user can switch between them. 该聊天应用程序一次将进行多个交互,用户可以在它们之间切换。

class Chat extends React.Component  {
 render() {
    return(
         //children components
    )

  }
}
ReactDom.render(<Chat/>,document.getElementById('app'))

I have a survey form component as a child component of the app. 我有一个调查表单组件作为该应用程序的子组件。 survey form is loaded inside an iframe and the contents of the form are loaded from server which are different for different interactions. 调查表单被加载到iframe中,并且表单的内容是从服务器加载的,这对于不同的交互而言是不同的。 So whenever a new interaction comes to user I re-render survey form component the whole thing with the new form data ( list of iframes in this case one for each interaction) . 因此,每当有新的交互作用出现时,我都会使用新的表单数据(在这种情况下,每个交互作用都包含一个iframe列表)重新呈现调查表单组件。

Now the problem is that it will render the initial form contents every time, let's say I have filled the first form and when a new interaction comes up (state change :rerender with the list) there will be 2 forms with initial content received from the server making me lose the data which I have filled. 现在的问题是它将每次都呈现初始表单内容,假设我已经填写了第一个表单,并且当出现新的交互(状态更改:带有列表的rerender)时,将有2种表单具有初始内容。服务器使我丢失了我已填写的数据。

Question : How can I retain this filled contents? 问题:如何保留此填充内容?

A probable solution would be storing the current form contents in a redux-store with the key as interaction and rendering it for the particular interaction, when the iframe unloads but I do not want to do that. 当iframe卸载但我不想这样做时,可能的解决方案是将当前表单内容存储在redux存储中,并以键作为交互,并为特定的交互呈现它。

Is there anyway where I can dynamically (on new interaction ) create a new div or any element and render the surveyformcomponent (containing single iframe) again so that other components are not re-rendered. 无论如何,我可以动态地(在新的交互作用下)创建一个新的div或任何元素,并再次渲染SurveyformComponent(包含单个iframe),以便不重新渲染其他组件。 So that there will be new iframe rendered inside a div without affecting the previously rendered iframes. 这样,在div内将渲染新的iframe,而不会影响以前渲染的iframe。

Thanks!! 谢谢!!

Its a stretch but you probably do another ReactDOM render call inside the componentDidMount lifecycle method of your parent class. 这很麻烦,但是您可能在父类的componentDidMount生命周期方法内执行了另一个ReactDOM渲染调用。 You could also us the lifecycle method shouldComponentUpdate to gain more control over the rerendering. 您也可以使用生命周期方法shouldComponentUpdate来获得对重新渲染的更多控制。

shouldCompnentUpdate(nextProps, nextState) {
  if (/*something changed and you need to rerender explicitly*/) {
     return true;
  } else {
    return false;
  }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM