I want to insert a new line (like \r\n, <br />) in a Text component in React Native.
我想在React Native的Text组件中插入一个新行(如\ r \ n,
)。
If I have:
如果我有:
<text><br />
Hi~<br >
this is a test message.<br />
</text>
Then React Native renders Hi~ this is a test message.
然后React Native呈现Hi~这是一条测试消息。
Is it possible render text to add a new line like so:
可以渲染文本添加新行,如下所示:
Hi~
this is a test message.
7 个解决方案
#1
275
I cannot test it right now but this should do it:
我现在无法测试它但是应该这样做:
<Text>
Hi~{"\n"}
this is a test message.
</Text>
#2
42
You can also do:
你也可以这样做:
<Text>{`
Hi~
this is a test message.
`}</Text>
Easier in my opinion, because you don't have to insert stuff within the string; just wrap it once and it keeps all your line-breaks.
在我看来更容易,因为你不必在字符串中插入东西;只需将其包裹一次,它就会保留所有换行符。
#3
9
This worked for me
这对我有用
<Text>{`Hi~\nthis is a test message.`}</Text>
(react-native 0.41.0)
(反应原生0.41.0)
#4
4
Use:
使用:
<Text>{`Hi,\nCurtis!`}</Text>
Result:
结果:
Hi,
嗨,
Curtis!
柯蒂斯!
#5
3
If at all you are displaying data from state variables, use this.
如果你正在显示状态变量的数据,请使用它。
<Text>{this.state.user.bio.replace('<br/>', '\n')}</Text>
#6
3
You can use {'\n'}
as line breaks. Hi~ {'\n'} this is a test message.
您可以使用{'\ n'}作为换行符。嗨〜{'\ n'}这是一条测试信息。
#7
1
I needed a one-line solution branching in a ternary operator to keep my code nicely indented.
我需要一个在三元运算符中分支的单行解决方案,以保持我的代码很好地缩进。
{foo ? `First line of text\nSecond line of text` : `Single line of text`}
Sublime syntax highlighting helps highlight the line-break character:
Sublime语法高亮显示有助于突出显示换行符:
#1
275
I cannot test it right now but this should do it:
我现在无法测试它但是应该这样做:
<Text>
Hi~{"\n"}
this is a test message.
</Text>
#2
42
You can also do:
你也可以这样做:
<Text>{`
Hi~
this is a test message.
`}</Text>
Easier in my opinion, because you don't have to insert stuff within the string; just wrap it once and it keeps all your line-breaks.
在我看来更容易,因为你不必在字符串中插入东西;只需将其包裹一次,它就会保留所有换行符。
#3
9
This worked for me
这对我有用
<Text>{`Hi~\nthis is a test message.`}</Text>
(react-native 0.41.0)
(反应原生0.41.0)
#4
4
Use:
使用:
<Text>{`Hi,\nCurtis!`}</Text>
Result:
结果:
Hi,
嗨,
Curtis!
柯蒂斯!
#5
3
If at all you are displaying data from state variables, use this.
如果你正在显示状态变量的数据,请使用它。
<Text>{this.state.user.bio.replace('<br/>', '\n')}</Text>
#6
3
You can use {'\n'}
as line breaks. Hi~ {'\n'} this is a test message.
您可以使用{'\ n'}作为换行符。嗨〜{'\ n'}这是一条测试信息。
#7
1
I needed a one-line solution branching in a ternary operator to keep my code nicely indented.
我需要一个在三元运算符中分支的单行解决方案,以保持我的代码很好地缩进。
{foo ? `First line of text\nSecond line of text` : `Single line of text`}
Sublime syntax highlighting helps highlight the line-break character:
Sublime语法高亮显示有助于突出显示换行符: