【问题标题】:How to replace \n new line character in string so that <p> tag can show new line如何替换字符串中的 \n 换行符,以便 <p> 标签可以显示换行符
【发布时间】:2019-04-04 09:44:27
【问题描述】:

在我正在处理的一个反应应用程序中,有一个条件:

当字符串有换行符时

要显示字符串的&lt;p&gt;{string}&lt;/p&gt;标签应替换为HTML换行符。

但这当然行不通。

我已经尝试过但对我不起作用的方法:

const string = Hello\nHii

  1. &lt;p&gt;{string.replace('\n', &lt;br /&gt;)}&lt;/p&gt;

输出:

Hello&lt;br /&gt;Hii

  1. &lt;p&gt;{string.replace('\n', &amp;amp;)}&lt;/p&gt;

输出:

Hello Hii

我在以下答案中找到了上述建议:

the val of a textarea doesnt take new lines into account

【问题讨论】:

标签: javascript html reactjs


【解决方案1】:

有两种选择。

  1. 使用pre标签或css属性white-space: pre

    &lt;p&gt;&lt;pre&gt;{string}&lt;/pre&gt;&lt;/p&gt;

  2. 使用dangerouslySetInnerHTML

    &lt;p dangerouslySetInnerHTML={{__html: string.replace('\n', '&lt;br /&gt;')}}&gt;&lt;/p&gt;

【讨论】:

    猜你喜欢
    • 2021-09-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-09-18
    • 2020-07-23
    • 2011-01-02
    相关资源
    最近更新 更多