繁体   English   中英

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

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

我有一个字符串,想在 React JS 中渲染它

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

我可以在 react js 中呈现这个 htmlString 请帮忙!

你可以使用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>;
  }
}

在这里查看文档

您可以在 html 元素上使用dangerouslySetInnerHTML属性将字符串设置为 HTML。但是要知道,在 React 中像这样设置 HTML 是有风险的,因为这可能会使您的用户面临跨站点脚本 (XSS) 攻击。 要了解有关如何使用它的更多信息,请参阅此处的官方 React 文档: https://reactjs.org/docs/dom-elements.html#dangerouslysetinnerhtml

在下面发布有关如何使用它的示例用例。

 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