我有一個字串,想在反應 JS 中呈現它
const htmlString = "<h1>
<Ref description=\"Magic may or may not be happening\"> hello magic</Ref></h1>"
return ( <div> <h1>
{htmlString}</h1>
</div\>)
我可以在反應js中渲染這個htmlString嗎?請幫忙!
uj5u.com熱心網友回復:
您可以使用庫 react-jsx-parser ( https://github.com/TroyAlford/react-jsx-parser ),README 中的示例看起來像您想要做的
uj5u.com熱心網友回復:
您可以使用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>;
}
}
在此處查看檔案
uj5u.com熱心網友回復:
您可以在 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>
);
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/qukuanlian/447823.html
標籤:javascript 反应 细绳 jsx 使成为
