我想在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~
this is a test message.
`}</Text>

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

如果你从状态变量或道具中获取数据,Text组件有一个minWidth, maxWidth样式道具。

例子

const {height,width} = Dimensions.get('screen');

const string = `This is the description coming from the state variable, It may long thank this` 

<Text style={{ maxWidth:width/2}}>{string}</Text>

这将显示屏幕宽度的50%的文本

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

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