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

当前回答

在数组中定义的文本行之间插入<br>的另一种方法:

import react, { Fragment } from 'react';

const lines = [
  'One line',
  'Another line',
];

const textContent =
  lines.reduce(items, line, index) => {
    if (index > 0) {
      items.push(<br key={'br-'+index}/>);
    }
    items.push(<Fragment key={'item-'+index}>{line}</Fragment>);
    return items;
  }, []);

然后文本可以作为变量使用:

<Text>{textContent}</Text>

如果不可用,Fragment可以这样定义:

const Fragment = (props) => props.children;

其他回答

编辑:

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

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

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

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

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

这应该做到:

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

在数组中定义的文本行之间插入<br>的另一种方法:

import react, { Fragment } from 'react';

const lines = [
  'One line',
  'Another line',
];

const textContent =
  lines.reduce(items, line, index) => {
    if (index > 0) {
      items.push(<br key={'br-'+index}/>);
    }
    items.push(<Fragment key={'item-'+index}>{line}</Fragment>);
    return items;
  }, []);

然后文本可以作为变量使用:

<Text>{textContent}</Text>

如果不可用,Fragment可以这样定义:

const Fragment = (props) => props.children;