如何将 /n 替换为 react.js 中的换行符?

IT技术 javascript reactjs ecmascript-6
2021-05-20 17:28:59

我想,以取代每/n一个<br>的标签ReactJS在我的note.note对象中有一个带有多个的字符串/n

示例note.note: test\ntest\ntest

我尝试过的ReactJS

{
  note.note.split('\n').map(function( item, idx) {
    return (
        <span key={idx}>
          {item}
          <br/>
        </span>
    )
  })
}
4个回答

另一种方法是使用 css 以换行符显示它。这也使复制和粘贴原始换行符以及区分一个中断 ( \n) 和两个中断 ( \n\n)变得更容易

只需将样式添加white-space: pre-wrap;到您的元素中即可。

<div style={{whiteSpace: "pre-wrap"}}>{note.note}</div>

如果这不能完全满足您的要求,还有其他空白选项:https : //developer.mozilla.org/en-US/docs/Web/CSS/white-space

您的代码运行良好:

{
    note.note.split("\n").map(function(item, idx) {
        return (
            <span key={idx}>
                {item}
                <br/>
            </span>
         )
    })
}

笔记:

OP 问题在于后端返回\\n并显示\nXHR preview选项卡中

我只想分享这个我已经使用了很长时间的功能。它类似于吉姆皮特斯的答案,但不会产生父标签,只需转动\n<br key="<index here>" />

import React from 'react'

export const escapedNewLineToLineBreakTag = (string) => {
  return string.split('\n').map((item, index) => {
    return (index === 0) ? item : [<br key={index} />, item]
  })
}

您还可以通过省略return和大括号将其转换为有点长的单行

export const escapedNewLineToLineBreakTag = (string) => string.split('\n').map((item, index) => (index === 0) ? item : [<br key={index} />, item])

免责声明:背后的逻辑不是来自我,但我不记得我在哪里找到的。我只是把它变成了函数形式。

另一种方法:

{
    note.note.split('\n').map((item, idx) => {
        return (
          <span key={idx}>
            {item}
            <br/>
          </span>
        );
    })
}