我有一个用例,在这里我需要格式化一些文本的反应和渲染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字符和\n。调用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>
));
}发布于 2020-01-14 10:35:45
<Fragment>不向DOM和you can't do dangerouslySetInnerHTML on it添加任何节点。它基本上是React提供的一种功能,当您需要在render中返回多个节点时,可以避免在DOM中添加额外的节点。因此,如果在真正的DOM中不存在某些东西,那么您就不能在它上做任何事情--。renderToString通常在节点服务器上使用。在执行服务器端呈现时,您希望将html从服务器发送到客户端。所以,最好也避免renderToString。问题是,html不识别新行等的\n,它需要html标记。使用FormatText的方法很好,或者您可以简单地使用convert the \n to br,然后在<li>标记中使用dangerouslySetInnerHTML。
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>
希望能帮上忙。回复任何疑问。
发布于 2020-01-14 10:35:26
嗨,我想这是不可能的,唯一的方式热传递格式的html到DOm是通过多姆元素DIV。
也许这个链接可以帮助你或者指向https://reactjs.org/docs/dom-elements.html
https://stackoverflow.com/questions/59731225
复制相似问题