简体   繁体   English

如何将react组件传递给危险地设置InnerHtml?

[英]How to pass react component into dangerouslySetInnerHtml?

Suppose I cannot change this statement in my sourcecode: 假设我无法在源代码中更改此语句:

<div dangerouslySetInnerHTML={{ __html: template }} />  

How can I replace the template for a react component? 如何替换React组件的模板? Like: 喜欢:

<div dangerouslySetInnerHTML={{ __html: someReactComponent }} />  

How can in insert a reactjs component in ? 如何在中插入reactjs组件?

As commented by FrankerZ , 正如FrankerZ所说

Why do you even have to do this? 您为什么还要这样做? <div><someReactComponent /></div> . <div><someReactComponent /></div> There's a reason why it uses the word "dangerously"...avoid using it if you have to. 为什么使用“危险”一词是有原因的...如果需要,请避免使用它。

Yes, obviously. 是的,显然。 You shouldn't be using dangerouslySetInnerHTML most of the time as far as possible. 您不应该在大多数时间都尽可能地dangerouslySetInnerHTML地使用dangerouslySetInnerHTML

If you are trying to render static markup, then you may use renderToStaticMarkup . 如果您尝试呈现静态标记,则可以使用renderToStaticMarkup The linked post has also stated that but will not work because it is being used from React instance. 链接的帖子还指出,但由于在React实例中被使用而无法正常工作。 You need to use it from ReactDOMServer : 您需要从ReactDOMServer使用它:

import ReactDOMServer from 'react-dom/server';
ReactDOMServer.renderToStaticMarkup(statticElement)

This doesn't create extra DOM attributes that React uses internally, such as data-reactroot. 这不会创建React内部使用的额外DOM属性,例如data-reactroot。 This is useful if you want to use React as a simple static page generator, as stripping away the extra attributes can save some bytes. 如果您想将React用作简单的静态页面生成器,这将很有用,因为去除多余的属性可以节省一些字节。

See the docs for more information on it. 有关更多信息,请参阅文档

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

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