从保存的文本区域反应显示换行符

React display line breaks from saved textarea

使用 Facebook React。 在设置页面中,我有一个多行 textarea,用户可以在其中输入多行文本(在我的例子中是一个地址)。

<textarea value={address} />

当我尝试显示地址时,例如 {address},它不显示换行符并且全部在一行中。

<p>{address}</p>

有什么解决办法吗?

这是意料之中的,您需要将新行 (\n) 字符转换为 HTML 换行符

关于在 React 中使用它的文章:React Newline to break (nl2br)

引用文章:

Because you know that everything in React is functions, you can't really do this

this.state.text.replace(/(?:\r\n|\r|\n)/g, '<br />')

Since that would return a string with DOM nodes inside, that is not allowed either, because has to be only a string.

You then can try do something like this:

{this.props.section.text.split(“\n”).map(function(item) {
  return (
    {item}
    <br/>
  )
})}    

That is not allowed either because again React is pure functions and two functions can be next to each other.

tldr. Solution

{this.props.section.text.split(“\n”).map(function(item) {
  return (
    <span>
      {item}
      <br/>
    </span>
  )
})}

Now we're wrapping each line-break in a span, and that works fine because span’s has display inline. Now we got a working nl2br line-break solution

没有理由使用 JS。您可以使用 white-space CSS 属性:

轻松告诉浏览器如何处理换行符
white-space: pre-line;

pre-line

Sequences of whitespace are collapsed. Lines are broken at newline characters, at <br>, and as necessary to fill line boxes.

看看这个演示:

<style>
  #p_wrap {
    white-space: pre-line;
  }
</style>

<textarea id="textarea"></textarea>
<p id="p_standard"></p>
<hr>
<p id="p_wrap"></p>
<script>
  textarea.addEventListener('keypress', function(e) {
    p_standard.textContent = e.target.value
    p_wrap.textContent = e.target.value
  })
</script>

解决方案是在显示内容的元素上设置 属性 white-space textarea:

white-space: pre-line;

从 React 16 开始,一个组件可以 return 一个元素数组,这意味着您可以像这样创建一个组件:

export default function NewLineToBr({children = ""}){
  return children.split('\n').reduce(function (arr,line) {
    return arr.concat(
      line,
      <br />
    );
  },[]);
}

您可以这样使用:

<p>
  <NewLineToBr>{address}</NewLineToBr>
</p>

Pete 之前关于独立组件的提议是很好的解决方案,尽管它遗漏了一件重要的事情。列出需求 keys。我稍微调整了一下,我的版本(没有控制台警告)如下所示:

const NewLineToBr = ({ children = '' }) => children.split('\n')
  .reduce((arr, line, index) => arr.concat(
    <Fragment key={index}>
      {line}
      <br />
    </Fragment>,
  ), [])

它使用 React 16 的 Fragments

喜欢网页版。我不知道 Fragment 组件,它非常有用。虽然不需要使用 reduce 方法。 地图就够了。此外, list 确实需要 react 中的键,但是使用迭代方法中的索引是坏习惯。 eslint 在我的警告中不断粉碎这个,直到我遇到混淆错误。 所以它看起来像这样:

const NewLine = ({ children }) =>
   children.split("\n").map(line => (
    <Fragment key={uuidv4()}>
      {line}
      <br />
    </Fragment>
  ));

对上述答案的一个小补充: white-space 属性 最好与 word-wrap 一起使用,以防止溢出。

p {
  white-space: pre-wrap;
  word-wrap: break-word;   
}