简体   繁体   English

设置危险地设置innerHtml时,如何从ReactJS中的html字符串呈现react组件?

[英]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.

相关问题 在后台从 React 组件制作 HTML 字符串,如何在另一个 React 组件中通过危险的SetInnerHTML 使用该字符串 - Making an HTML string from a React component in background, how to use the string by dangerouslySetInnerHTML in another React component 如何在危险的SetInnerHTML 内容中呈现反应组件? - How to Render a react component inside a dangerouslySetInnerHTML content? 用React.js组件替换部分html字符串并渲染(没有dangerouslySetInnerHTML) - Replace part of html string with React.js component and render (without dangerouslySetInnerHTML) React Render HTML代码(dangerouslySetInnerHTML?) - React Render HTML Code (dangerouslySetInnerHTML?) 在React中危险地渲染带有JSX表达式的HTML字符串SetInnerHTML() - Render HTML string w/JSX expression in React dangerouslySetInnerHTML() 如何在 React JS 中将 HTML 字符串呈现给组件 - How to render HTML string to component in React JS 反应使用危险的SetInnerHTML 渲染带有 html 标签的 json - react use dangerouslySetInnerHTML to render json with html tags 是否可以在不使用 dangerouslySetInnerHtml 的情况下渲染 HTML - Is it possible to render HTML in react without using dangerouslySetInnerHtml React:如何从组件的 state 设置`dangerouslySetInnerHTML`? - React: how to set `dangerouslySetInnerHTML` from component's state? 在由 dangerouslySetInnerHTML 设置的 HTML 中添加 React 组件 - Add React component in HTML set by dangerouslySetInnerHTML
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM