简体   繁体   English

如何将反应组件转换为 html 字符串?

[英]How to convert react component to html string?

I have found similar to my issue here .在这里发现了类似于我的问题。

But I have a little bit different scenario.但我有一些不同的场景。 I have string of html rather than just string.我有 html 字符串,而不仅仅是字符串。 So, I wanted to do:所以,我想做:

Let's suppose MyComponent is just returning h3 element for now:让我们假设 MyComponent 现在只是返回 h3 元素:

const MyComponent = ({children}) => (<h3>{children}</h3>)

var parts = "<h1>I</h1><p>am a cow;</p>cows say moo. MOOOOO."
    .split(/(\bmoo+\b)/gi);
for (var i = 1; i < parts.length; i += 2) {
  parts[i] = <MyComponent key={i}>{parts[i]}</MyComponent>;
}
// But I need html to be rendered
return <div dangerouslySetInnerHTML={{ __html: parts }} />

This will be rendered in the browser like this:这将在浏览器中呈现如下:

I
am a cow;
cows say ,[object Object],. ,[object Object],.

What I can think here to resolve the issue is converting component with string of html first.我在这里能想到的解决这个问题的方法是首先用 html 字符串转换组件。

parts[i] = convertToStringOfHtml(<MyComponent key={i}>{parts[i]}</MyComponent>);

But I don't have idea how to convert component to string of html.但我不知道如何将组件转换为 html 字符串。

You can do with react-dom你可以用 react-dom 做

import { renderToString } from 'react-dom/server'
//
//
parts[i] = renderToString(<MyComponent key={i}>{parts[i]}</MyComponent>)

view more here https://reactjs.org/docs/react-dom-server.html在此处查看更多信息https://reactjs.org/docs/react-dom-server.html

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

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