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

当前回答

你可以这样做:

{'创建\ nYour帐户'}

其他回答

这是一个很好的问题,你可以用多种方法来做这个问题 第一个

<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>

这意味着你可以使用另一个<查看>组件里面首先<查看>和包装它周围<文本>组件

快乐的编码

React不喜欢你把HTML <br />放在它需要文本的地方,而且\ns并不总是被渲染,除非在<pre>标记中。

也许可以像这样将每个断行字符串(段落)包装在<p>标记中:

{text.split("\n").map((line, idx) => <p key={idx}>{line}</p>)}

如果你在迭代React组件,不要忘记键。

这段代码适用于我的环境。(react-native 0.63.4)

const charChangeLine = `
`
// const charChangeLine = "\n" // or it is ok

const textWithChangeLine = "abc\ndef"

<Text>{textWithChangeLine.replace('¥n', charChangeLine)}</Text>

结果

abc
def

我知道这是相当古老的,但我提出了一个自动断行的解决方案,允许您以通常的方式传递文本(没有诡计)

我创建了以下组件

import React, {} from "react";
import {Text} from "react-native";

function MultiLineText({children,  ...otherProps}) {

const splits = children.split("\\n")
console.log(splits);
const items = []
for (let s of splits){
  items.push(s)
  items.push("\n")
}

  return (
    <Text {...otherProps}>{items}</Text>
  );
}


export default MultiLineText;

然后你就可以这样使用它了。

<MultiLineText style={styles.text}>This is the first line\nThis is teh second line</MultiLineText>

如果有人正在寻找一个解决方案,你想要在数组中的每个字符串有一个新的行,你可以这样做:

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- nativenew -break-line-example