我想在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>
Hi~{"\n"}
this is a test message.
</Text>

最好的方法使用列表,如UL或OL,并做一些样式,如使列表样式none,你可以使用<li> dhdhhd </li>

你可以试试这样用

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

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

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

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

<Text>

   Hello {'\n'}

   World!

</Text>