简体   繁体   English

如何在具有组件的 React JS 中呈现字符串?

[英]How can I render a string in React JS which has components?

I have a String and want to render it in react JS我有一个字符串,想在 React JS 中渲染它

const htmlString = "<h1>
<Ref description=\"Magic may or may not be happening\"> hello magic</Ref></h1>"
return ( <div> <h1>
{htmlString}</h1>
 </div\>)

Can I render this htmlString in react js Please help!我可以在 react js 中呈现这个 htmlString 请帮忙!

You can use react-html-parser to achieve this你可以使用react-html-parser来实现这个

import React from 'react';
import ReactHtmlParser from 'react-html-parser';
 
class HtmlComponent extends React.Component {
  render() {
    const html = '<div>Example HTML string</div>';
    return <div>{ ReactHtmlParser(html) }</div>;
  }
}

See docs here在这里查看文档

You can use dangerouslySetInnerHTML attribute on an html element to set the string as HTML. But know that setting HTML like this in React is risky as this may expose your users to a cross-site scripting (XSS) attack.您可以在 html 元素上使用dangerouslySetInnerHTML属性将字符串设置为 HTML。但是要知道,在 React 中像这样设置 HTML 是有风险的,因为这可能会使您的用户面临跨站点脚本 (XSS) 攻击。 To know more on how to use it, refer here on official React docs: https://reactjs.org/docs/dom-elements.html#dangerouslysetinnerhtml要了解有关如何使用它的更多信息,请参阅此处的官方 React 文档: https://reactjs.org/docs/dom-elements.html#dangerouslysetinnerhtml

Posting an example use-case below on how to use it.在下面发布有关如何使用它的示例用例。

 function App() { function getMarkup() { return {__html: '<h3>My Content here..</h3>'}; // The HTML string you want to set } return ( <div className="App"> <div dangerouslySetInnerHTML={getMarkup()}></div> </div> ); }

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

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