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

当前回答

这是一个很好的问题,你可以用多种方法来做这个问题 第一个

<View>
    <Text>
        Hi this is first line  {\n}  hi this is second line 
    </Text>
</View>

这意味着您可以使用{\n}反斜杠n来断行

第二个

<View>
     <Text>
         Hi this is first line
     </Text>
     <View>
         <Text>
             hi this is second line 
         </Text>
     </View>
</View>

这意味着你可以使用另一个<查看>组件里面首先<查看>和包装它周围<文本>组件

快乐的编码

其他回答

你可以试试这样用

<text>{`${val}\n`}</text>

如果有人正在寻找一个解决方案,你想要在数组中的每个字符串有一个新的行,你可以这样做:

import * as React from 'react';
import { Text, View} from 'react-native';


export default class App extends React.Component {
  constructor(props) {
    super(props);

    this.state = {
      description: ['Line 1', 'Line 2', 'Line 3'],
    };
  }

  render() {
    // Separate each string with a new line
    let description = this.state.description.join('\n\n');

    let descriptionElement = (
      <Text>{description}</Text>
    );

    return (
      <View style={{marginTop: 50}}>
        {descriptionElement}
      </View>
    );
  }
}

请参阅小吃现场示例:https://snack.expo.io/@cmacdonnacha/react- nativenew -break-line-example

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

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

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

你可以像这样使用' ':

<Text>{`Hi~
this is a test message.`}</Text>

只需在Text标签中放入{'\n'}

<Text>

   Hello {'\n'}

   World!

</Text>