[英]ReactJS convert HTML string to JSX
我在處理 facebook 的 ReactJS 時遇到問題。每當我執行 ajax 並想要顯示 html 數據時,ReactJS 會將其顯示為文本。 (見下圖)
通過jquery Ajax的成功回調function顯示數據。
$.ajax({
url: url here,
dataType: "json",
success: function(data) {
this.setState({
action: data.action
})
}.bind(this)
});
有什么簡單的方法可以將其轉換為 html 嗎? 我應該如何使用 ReactJS 進行操作?
默認情況下,React 會轉義 HTML 以防止XSS(跨站點腳本) 。 如果你真的想渲染 HTML,你可以使用dangerouslySetInnerHTML
屬性:
<td dangerouslySetInnerHTML={{__html: this.state.actions}} />
React 強制使用這種有意繁瑣的語法,這樣您就不會意外地將文本呈現為 HTML 並引入 XSS 錯誤。
現在有更安全的方法來實現這一點。 文檔已使用這些方法進行了更新。
其他方法
最簡單- 使用 Unicode,將文件另存為 UTF-8,並將charset
設置為 UTF-8。
<div>{'First · Second'}</div>
更安全- 對 Javascript 字符串中的實體使用 Unicode 編號。
<div>{'First \· Second'}</div>
或者
<div>{'First ' + String.fromCharCode(183) + ' Second'}</div>
或者帶有字符串和 JSX 元素的混合數組。
<div>{['First ', <span>·</span>, ' Second']}</div>
最后的手段- 使用dangerouslySetInnerHTML
SetInnerHTML 插入原始 HTML。
<div dangerouslySetInnerHTML={{__html: 'First · Second'}} />
我建議使用交織產生的milesj 。 它是一個非凡的庫,它利用了一些巧妙的技術來解析 HTML 並將其安全地插入到 DOM 中。
Interweave 是一個反應庫,可以安全地呈現 HTML、過濾屬性、使用匹配器自動換行文本、呈現表情符號字符等等。
用法示例:
import React from 'react';
import { Markup } from 'interweave';
const articleContent = "<p><b>Lorem ipsum dolor laboriosam.</b> </p><p>Facere debitis impedit doloremque eveniet eligendi reiciendis <u>ratione obcaecati repellendus</u> culpa? Blanditiis enim cum tenetur non rem, atque, earum quis, reprehenderit accusantium iure quas beatae.</p><p>Lorem ipsum dolor sit amet <a href='#testLink'>this is a link, click me</a> Sunt ducimus corrupti? Eveniet velit numquam deleniti, delectus <ol><li>reiciendis ratione obcaecati</li><li>repellendus culpa? Blanditiis enim</li><li>cum tenetur non rem, atque, earum quis,</li></ol>reprehenderit accusantium iure quas beatae.</p>"
<Markup content={articleContent} /> // this will take the articleContent string and convert it to HTML markup. See: https://milesj.gitbook.io/interweave
//to install package using npm, execute the command
npm install interweave
npm i html-react-parser;
import Parser from 'html-react-parser';
<td>{Parser(this.state.archyves)}</td>
對於那些仍在試驗中的人, npm install react-html-parser
當我安裝它時,它每周有 123628 次下載。
import ReactHtmlParser from 'react-html-parser'
<div>{ReactHtmlParser(htmlString)}</div>
如果要在 React 中呈現原始 html,可以使用以下命令
<div dangerouslySetInnerHTML={{__html: `html-raw-goes-here`}} />
示例 - 渲染
考試是個好日子
我發現了這個 js 小提琴。 這就像這樣
function unescapeHTML(html) {
var escapeEl = document.createElement('textarea');
escapeEl.innerHTML = html;
return escapeEl.textContent;
}
<textarea className="form-control redactor"
rows="5" cols="9"
defaultValue={unescapeHTML(this.props.destination.description)}
name='description'></textarea>
jsfiddle鏈接
您還可以使用 html-react-parser 中的 Parser()。 我也用過。 鏈接共享。
我開始使用名為 react-html-parser 的 npm 包
這可以通過使用像這樣放置在這個塊{[]}
的內容來解決。 為了更清楚,可以在下面引用示例。
{[
'abc',
<b>my bold</b>,
'some other text'
]}
這將保留標簽下文本的格式,而其他文本將作為純文本打印。
如果您事先知道要呈現的字符串中有哪些標簽; 例如,如果在創建字符串時只允許某些標簽; 解決此問題的一種可能方法是使用 Trans 實用程序:
import { Trans } from 'react-i18next'
import React, { FunctionComponent } from "react";
export type MyComponentProps = {
htmlString: string
}
export const MyComponent: FunctionComponent<MyComponentProps> = ({
htmlString
}) => {
return (
<div>
<Trans
components={{
b: <b />,
p: <p />
}}
>
{htmlString}
</Trans>
</div>
)
}
然后你可以像往常一樣使用它
<MyComponent
htmlString={'<p>Hello <b>World</b></p>'}
/>
這很簡單。
它工作得很好。
import {settings} from '../settings'; const NavBar = (props) => { let isLoggedIn=props.isLoggedIn; let login_partial = ""; if(isLoggedIn) {login_partial= <li>Log Out</li>;} else{ login_partial= <div> <li>Login</li> <li>Sign Up</li> </div>; } return( <div> <ul> <li>Home</li> <li>Products</li> {login_partial} </ul> </div> ) } export default NavBar;
現有答案中缺少的一個選項是使用<React.Fragment>
(在 React v16 及更高版本中可用)。 我覺得這是最好的,因為這允許您將任何 html 元素存儲為 JSX 變量並在以后引用它。 也因為使用dangerouslySetInnerHTML
是不安全的。
例如
const App = () => { const Windows = <React.Fragment>Microsoft <abbr title="Operating System">OS</abbr></React.Fragment> return ( <ul> <li>{Windows}</li> </ul> ); }; ReactDOM.render(<App />, document.getElementById("root"));
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.3/umd/react.production.min.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.3/umd/react-dom.production.min.js"></script> <div id="root"></div>
<></>
,它是<React.Fragment></React.Fragment>
的簡寫dangerouslySetInnerHTML
很危險,因為惡意客戶端代碼可以通過腳本標簽注入: https : //stackoverflow.com/a/42380982/6908282
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.