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

当前回答

嘿,把它们这样放,这对我很有用!

< div > <p style={{fontWeight: "bold",空格:"pre-wrap"}}> {"} 你好{" \ n "} < / p > {" \ n "} <p>我在这里</p> < / div >

其他回答

如果你想在元素中使用变量,你可以试试这个。

<文本> {newText} < /短信>

const newText= text.body.split("\n")。Map ((item, key) => { 回报( < span关键={关键}> {项} < br / > < / span > ); });

编辑:

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

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

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

(请注意使用反引号)

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

会导致

Hi~
This is a test message

嘿,把它们这样放,这对我很有用!

< div > <p style={{fontWeight: "bold",空格:"pre-wrap"}}> {"} 你好{" \ n "} < / p > {" \ n "} <p>我在这里</p> < / div >

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

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