Cur*_*tis 262 javascript text newline react-native
我想在React Native的Text组件中插入一个新行(如\ r \n,<br />).
如果我有:
<text><br />
Hi~<br >
this is a test message.<br />
</text>
然后React Native渲染 Hi~ this is a test message.
是否可以渲染文本添加新行,如下所示:
Hi~
this is a test message.
Chr*_*nea 525
我现在无法测试它但是应该这样做:
<Text>
Hi~{"\n"}
this is a test message.
</Text>
Ven*_*ryx 80
你也可以这样做:
<Text>{`
Hi~
this is a test message.
`}</Text>
在我看来更容易,因为你不必在字符串中插入东西; 只需将其包裹一次,它就会保留所有换行符.
Muh*_*man 64
<Text>
  line 1{"\n"}
  line 2
</Text>
 <Text>{`
  line 1
  line 2
 `}</Text>
这是我处理多个<br/>标签的解决方案:
<Text>
  line 1{"\n"}
  line 2
</Text>
用于maxWidth自动换行
<Text style={{ maxWidth:200}}>this is a test message. this is a test message</Text>
小智 26
使用:
<Text>{`Hi,\nCurtis!`}</Text>
结果:
嗨,
柯蒂斯!
Oli*_*ier 13
这对我有用
<Text>{`Hi~\nthis is a test message.`}</Text>
(反应原生0.41.0)
Edi*_*uza 10
如果您要显示状态变量的数据,请使用此选项.
<Text>{this.state.user.bio.replace('<br/>', '\n')}</Text>
我需要一个在三元运算符中分支的单行解决方案,以保持我的代码很好地缩进。
{foo ? `First line of text\nSecond line of text` : `Single line of text`}
Sublime 语法突出显示有助于突出显示换行符:
更好的是:如果你使用styled-components,你可以做这样的事情:
import React, { Component } from 'react';
import styled from 'styled-components';
const Text = styled.Text`
  text-align: left;
  font-size: 20px;
`;
export default class extends Component {
 (...)
 render(){
  return (
    <View>
      <Text>{`
        1. line 1
        2. line 2
        3. line 3
      `}</Text>
    </View>
  );
 }
}
小智 6
这是一个很好的问题,您可以通过多种方式 首先做到这一点
<View>
    <Text>
        Hi this is first line  {\n}  hi this is second line 
    </Text>
</View>
这意味着您可以使用{\n}反斜杠 n 来换行
第二
<View>
     <Text>
         Hi this is first line
     </Text>
     <View>
         <Text>
             hi this is second line 
         </Text>
     </View>
</View>
这意味着您可以在第一个<View>内部使用另一个<View>组件,并将其包裹在 <Text>组件周围
快乐编码
/sf/answers/3139206731/ @Edison D'souza 的回答正是我想要的。但是,它只是替换了第一次出现的字符串。这是我处理多个<br/>标签的解决方案:
<Typography style={{ whiteSpace: "pre-line" }}>
    {shortDescription.split("<br/>").join("\n")}
</Typography>
抱歉,由于声誉分数限制,我无法对他的帖子发表评论。
小智 5
有两种选择:
选项 1:使用模板文字。
const Message = 'This is a message';
<Text>
{`
  Hi~
  ${Message}
`}
</Text>
结果:
Hi~
This is a message
选项 2:使用 {'\n'} 作为换行符。
<Text>
   Hello {'\n'}
   World!
</Text>
结果:
Hello
World!
| 归档时间: | 
 | 
| 查看次数: | 243759 次 | 
| 最近记录: |