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

当前回答

为什么这么努力工作?现在是2020年,创建一个组件来处理这类问题

    export class AppTextMultiLine extends React.PureComponent {
    render() {
    const textArray = this.props.value.split('\n');
return (
        <View>
            {textArray.map((value) => {
               return <AppText>{value}</AppText>;
            })}
        </View>
    )
}}

其他回答

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

这应该做到:

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

你还可以:

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

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

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

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

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

如果你从状态变量或道具中获取数据,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%的文本