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

当前回答

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

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

其他回答

这应该做到:

<Text>
Hi~{"\n"}
this is a test message.
</Text>
<Text>
Hi~{"\n"}
this is a test message.
</Text>

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

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

(请注意使用反引号)

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>

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

你还可以:

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

在我看来更简单,因为你不需要在字符串中插入东西;只要换行一次,就能保留所有换行符。