如何在React Native中的组件中插入换行符?

我想在React Native的文本组件中插入一个新行(如\r\n,
)。

如果我有

<text><br />
Hi~<br >
this is a test message.<br />
</text>

那么React Native就会渲染 "Hi~这是一条测试信息"。

是否可以像这样渲染文本,添加新的一行。

Hi~
this is a test message.
解决办法

这应该可以了。


Hi~{"\n"}
this is a test message.
评论(8)

你也可以这样做。

{`
Hi~
this is a test message.
`}

在我看来,这更容易,因为你不必在字符串中插入东西;只需将它包起来一次,就能保留所有的换行符。

评论(6)

使用。

{`Hi,\nCurtis!`}

结果。

柯蒂斯!

评论(2)

这对我来说很有效

{`Hi~\nthis is a test message.`}

(react-native 0.41.0)

评论(0)

如果您要显示来自状态变量的数据,请使用这个。

{this.state.user.bio.replace('<br/>', '\n')}
评论(0)

你可以使用{&#39;\n&#39;}作为换行符。

Hi~ {'\n'}这是一条测试信息。
评论(0)

更好的是,如果你使用 "styled-components",你可以做这样的事情: 如果你使用 "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 (

      {`
        1. line 1
        2. line 2
        3. line 3
      `}

  );
 }

}
评论(0)

你可以试试这样使用

{`${val}\n`}
评论(0)

我需要一个单行解决方案,在三元操作符中进行分支,以使我的代码保持良好的缩进。

{foo ? `First line of text\nSecond line of text` : `Single line of text`}

崇高的语法高亮有助于突出显示断行字符。

[! [崇高语法高亮][1]][1]

[1]: https://i.stack.imgur.com/nV1xt.png

评论(0)

你也可以将它作为一个常量添加到你的渲染方法中,这样就很容易重复使用。

  render() {
    const br = `\n`;
     return (
        Capital Street{br}Cambridge{br}CB11 5XE{br}United Kingdom
     )  
  }
评论(0)

你可以这样用``。

{`Hi~
this is a test message.`}
评论(0)

您可以按以下方式进行。

{'Createn/Your Account'}
评论(1)

只需将{&#39;\n&#39;}放在文本标签内即可。



   Hello {'\n'}

   World!

评论(0)

如果有人想为数组中的每一个字符串添加一行新的字符串,你可以这样做。

import * as React from 'react';
import { Text, View} from 'react-native';

export default class App extends React.Component {
  constructor(props) {
    super(props);

    this.state = {
      description: ['Line 1', 'Line 2', 'Line 3'],
    };
  }

  render() {
    // Separate each string with a new line
    let description = this.state.description.join('\n\n');

    let descriptionElement = (
      {description}
    );

    return (

        {descriptionElement}

    );
  }
}

实例请看点心。 https://snack.expo.io/@cmacdonnacha/react-native-new-break-line-example

评论(0)

我'用的是react js。 以上答案对我来说都不适用,但结合起来就可以了。 在native上应该也能用。 下面的代码。

//react js

<div style={{ whiteSpace: 'pre-wrap' }}>
 {`hello \nthere`}
</div>

//native (haven't tested but, technically should work...)



 {`hello \nthere`}
评论(0)

只要在你想断行的地方使用{"/n"}即可。

评论(0)

在文本中使用 "n",在css中使用 "white-space"。 pre-wrap;`

评论(1)