[英]React dangerouslySetInnerHTML Inside Fragment
我有一個用例,我需要在 React 中格式化一些文本並渲染 HTML。
這是我目前正在努力實現的一個例子:
import React, {Fragment} from "react";
import {renderToString} from "react-dom/server";
function FormatText(props) {
const lines = props.children.split('\n');
return lines.map((line, index) => (
<Fragment key={index}>
{line}{index !== lines.length - 1 && <br/>}
</Fragment>
));
}
const content = {
first: 'This is some text\nwith new\n\nline characters - 1',
second: 'This is some text\nwith new\n\nline <strong>characters - <sup>2</sup></strong>',
};
function App() {
return (
<ol>
<li>
<FormatText>{content.first}</FormatText>
</li>
<li dangerouslySetInnerHTML={{
__html: renderToString(<FormatText>{content.second}</FormatText>)
}}/>
</ol>
)
}
正如你所看到的,我有一些content
包含\\n
字符和HTML。 調用renderToString
函數會將 HTML 轉換為編碼字符,這意味着 HTML 未正確呈現。
有沒有辦法在反應片段中呈現 HTML。
理想情況下,我想做以下事情(但不是):
function FormatText(props) {
const lines = props.children.split('\n');
return lines.map((line, index) => (
<Fragment key={index} dangerouslySetInnerHTML={{__html: renderToString(
<Fragment>
{line}{index !== lines.length - 1 && <br/>}
</Fragment>
)}}>
</Fragment>
));
}
<Fragment>
不會向 DOM 添加任何節點,因此you can't do dangerouslySetInnerHTML on it
。 它基本上是 React 提供的一項功能,當您需要從渲染中的 return 返回多個節點時,它可以避免向 DOM 添加額外的節點。 所以,如果真實的 DOM 上不存在某些東西,你就不能對它做任何事情。renderToString
一般用在節點服務器上。 在進行服務器端渲染時,您希望將 html 從服務器發送到客戶端。 所以,最好也避免renderToString
。 問題是,html 無法識別新行等的\\n
。它需要html標簽。 使用FormatText
方法很好,或者您可以簡單地convert the \\n to br
,然后在<li>
標簽內使用危險的<li>
。
const content = { first: 'This is some text\\nwith new\\n\\nline characters - 1', second: 'This is some text\\nwith new\\n\\nline <strong>characters - <sup>2</sup></strong>', }; function App() { return ( <ol> <li dangerouslySetInnerHTML={{ __html: content.first.replace(/\\n/g, "<br/>") }}/> <li dangerouslySetInnerHTML={{ __html: content.second.replace(/\\n/g, "<br/>") }}/> </ol> ) } ReactDOM.render(<App/>, document.getElementById("root"))
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.1/umd/react.production.min.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.1/umd/react-dom.production.min.js"></script> <div id="root"></div>
希望能幫助到你。 如有任何疑問,請回復。
嗨,我想這是不可能的,將格式化的 html 傳遞到 DOm 的唯一方法是通過 dom 元素 DIV。
也許此鏈接可以幫助您或指向https://reactjs.org/docs/dom-elements.html
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.