[英]How to render a react component from html string in ReactJS while setting in dangerouslysetinnerHtml?
I am trying to load a component dynamically from html string. 我正在尝试从html字符串动态加载组件。 for example: I am having a html string like following which is from json. 例如:我有一个如下的html字符串,它来自json。
<div>This is some html content having a component of <Combobox params="option1,option2,option3"/></div>
here <Combobox params="option1,option2,option3"/>
is a React component which i need to render as a HTML combobox with options 1,2 and 3 along with the texts. 这里<Combobox params="option1,option2,option3"/>
是一个React组件,我需要将其渲染为带有选项1,2和3以及文本的HTML组合框。 So, is there any way to do this kind of things in React. 因此,在React中有什么方法可以做这种事情。
The entire JSX can be parsed to HTML using renderToString method. 可以使用renderToString方法将整个JSX解析为HTML。
import ReactDOMServer from 'react-dom/server';
render() {
const html = ReactDOMServer.renderToString(<div><Combobox /></div>);
return (
<div dangerouslySetInnerHTML={html}></div>
);
}
To build on vijayst's answer , if you're using redux/react-redux, and this happens to be a "connected" component, you'll need to import and pass the store along again. 要以vijayst的答案为基础,如果您使用的是redux / react-redux,而这恰好是“已连接”的组件,则需要再次导入并传递商店。
import ReactDOMServer from 'react-dom/server';
import { Provider } from 'react-redux';
import store from '../redux/store';
render() {
const html = ReactDOMServer.renderToString(<Provider store={store}><Combobox /></Provider>);
return <div dangerouslySetInnerHTML={html}></div>;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.