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

问题描述 投票:209回答:13

我想在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.
javascript text react-native newline
13个回答
478
投票

我现在无法测试它但是应该这样做:

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

1
投票

你可以使用``这样:

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

1
投票

你可以这样做:

{'创建您的帐户'}


1
投票

您也可以在渲染方法中将其添加为常量,以便于重用:

  render() {
    const br = `\n`;
     return (
        <Text>Capital Street{br}Cambridge{br}CB11 5XE{br}United Kingdom</Text>
     )  
  }

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 = (
      <Text>{description}</Text>
    );

    return (
      <View style={{marginTop: 50}}>
        {descriptionElement}
      </View>
    );
  }
}

查看小吃的实例:https://snack.expo.io/@cmacdonnacha/react-native-new-break-line-example


-5
投票

在文本和css \n中使用white-space: pre-wrap;


71
投票

你也可以这样做:

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

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


24
投票

使用:

<Text>{`Hi,\nCurtis!`}</Text>

结果:

嗨,

柯蒂斯!


13
投票

这对我有用

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

(反应原生0.41.0)


9
投票

您可以使用{'\n'}作为换行符。嗨〜{'\ n'}这是一条测试信息。


8
投票

如果您要显示状态变量的数据,请使用此选项。

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

3
投票

你可以尝试这样使用

<text>{`${val}\n`}</text>

3
投票

更好的是:如果你使用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>
  );
 }

}

2
投票

我需要在三元运算符中分支的单行解决方案,以保持我的代码很好地缩进。

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

Sublime语法高亮显示有助于突出显示换行符:

Sublime syntax highlight

© www.soinside.com 2019 - 2024. All rights reserved.