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

当前回答

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

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

(请注意使用反引号)

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

会导致

Hi~
This is a test message

其他回答

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

我创建了以下组件

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>

2021,这适用于REACT状态值(你必须添加空divs,就像返回语句一样)

这一点。setState({form:(<> line 1 <br /> line 2 </>)})

编辑:

如果你使用模板字面值(参见<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>
  );
 }
}

可以使用{'\n'}作为换行符。 嗨~ {'\n'}这是一个测试消息。

解决方案1:

<Text>
  line 1{"\n"}
  line 2
</Text>

解决方案2:

 <Text>{`
  line 1
  line 2
 `}</Text>

解决方案3:

以下是我处理多个<br/>标签的解决方案:

<Text style={{ whiteSpace: "pre-line" }}>
    {"Hi<br/> this is a test message.".split("<br/>").join("\n")}
</Text>

解决方案4:

使用maxWidth自动换行

<Text style={{ maxWidth:200}}>this is a test message. this is a test message</Text>