简体   繁体   English

在dangerouslySetInnerHTML中反应组件

[英]React component inside dangerouslySetInnerHTML

In my application, I need to get an HTML string. 在我的应用程序中,我需要获取一个HTML字符串。
(From the server or from the user input, maybe something processed from markdown, in any case, it seems I really need to use setDangerousHtml .) (从服务器或用户输入,也许是从markdown处理的东西,无论如何,似乎我真的需要使用setDangerousHtml 。)

But I also need some react components inside that part. 但我也需要在该部分内部使用一些反应组件。
For example, I would transform some links to Link from react-router; 例如,我会将一些链接转换为来自react-router的Link ; or I have something inside the HTML like <myWidget:12345> to a react component <MyWidget id="12345" text=this.props.text > . 或者我在HTML中有一些内容,如<myWidget:12345>到一个反应组件<MyWidget id="12345" text=this.props.text >

What is the react-way for doing this? 这样做的反应方式是什么?

One of the way to approach this problem is using RenderToString function. 解决此问题的方法之一是使用RenderToString函数。 Convert the component that you want to insert into a string like this: 将要插入的组件转换为如下字符串:

import React, { Component } from 'react';
import { renderToString } from 'react-dom/server';
import MyComponent from 'MyComponent.jsx';

var MyComponentString = renderToString(MyComponent);

Now concat this string into the string that's coming from the API wherever you want. 现在将此字符串连接到来自API的字符串,无论您想要什么。 Use basic string manipulation functions to achieve that. 使用基本的字符串操作函数来实现它。

Then, use setDangerousHtml to achieve the final new DOM. 然后,使用setDangerousHtml来实现最终的新DOM。 Although this might not be the recommended way for doing this, because RenderToString isn't supposed to be used in browser, it'll work. 虽然这可能不是推荐的方法,因为RenderToString不应该在浏览器中使用,它会起作用。

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

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