我想在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.

当前回答

编辑:

如果你使用模板字面值(参见<Text>元素),你也可以像这样添加换行符:

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

export default class extends Component {

 (...)

 render(){
  return (
    <View>
      <Text>{`
        1. line 1
        2. line 2
        3. line 3
      `}</Text>
    </View>
  );
 }
}

其他回答

你可以这样做:

{'创建\ nYour帐户'}

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

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

这样做:

<文本> {“嗨,这是一个测试消息。”} <文本/ >

最干净和最灵活的方法之一是使用模板字面量。

使用它的一个优点是,如果你想在文本体中显示字符串变量的内容,它更干净和直接。

(请注意使用反引号)

const customMessage = 'This is a test message';
<Text>
{`
  Hi~
  ${customMessage}
`}
</Text>

会导致

Hi~
This is a test message

https://stackoverflow.com/a/44845810/10480776 @Edison D'souza的答案正是我一直在寻找的。但是,它只是替换字符串的第一次出现。下面是我处理多个<br/>标签的解决方案:

<Typography style={{ whiteSpace: "pre-line" }}>
    {shortDescription.split("<br/>").join("\n")}
</Typography>

抱歉,由于声誉评分限制,我无法评论他的帖子。