我想在React Native的文本组件中插入一个新行(如\r\n, <br />)。

如果我有:

<text>
<br />
Hi~<br />
this is a test message.<br />
</text>

然后React Native渲染Hi~这是一个测试消息。

它是可能的渲染文本添加一个新的行像这样:

Hi~
this is a test message.

当前回答

React不喜欢你把HTML <br />放在它需要文本的地方,而且\ns并不总是被渲染,除非在<pre>标记中。

也许可以像这样将每个断行字符串(段落)包装在<p>标记中:

{text.split("\n").map((line, idx) => <p key={idx}>{line}</p>)}

如果你在迭代React组件,不要忘记键。

其他回答

你也可以把它作为一个常量添加到你的渲染方法中,这样很容易重用:

  render() {
    const br = `\n`;
     return (
        <Text>Capital Street{br}Cambridge{br}CB11 5XE{br}United Kingdom</Text>
     )  
  }

我使用p标签的新行。这里我粘贴了代码,这对大家都有帮助。

const new2DArr =  associativeArr.map((crntVal )=>{
          return <p > Id :  {crntVal.id} City Name : {crntVal.cityName} </p>;
     });

我知道这是相当古老的,但我提出了一个自动断行的解决方案,允许您以通常的方式传递文本(没有诡计)

我创建了以下组件

import React, {} from "react";
import {Text} from "react-native";

function MultiLineText({children,  ...otherProps}) {

const splits = children.split("\\n")
console.log(splits);
const items = []
for (let s of splits){
  items.push(s)
  items.push("\n")
}

  return (
    <Text {...otherProps}>{items}</Text>
  );
}


export default MultiLineText;

然后你就可以这样使用它了。

<MultiLineText style={styles.text}>This is the first line\nThis is teh second line</MultiLineText>

最好的方法使用列表,如UL或OL,并做一些样式,如使列表样式none,你可以使用<li> dhdhhd </li>

我需要一个在三元运算符中分支的单行解决方案,以保持我的代码很好地缩进。

{foo ? `First line of text\nSecond line of text` : `Single line of text`}

Sublime语法高亮显示有助于突出显示换行字符: