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

时间:2015-09-09 01:29:13

标签: javascript text react-native newline

我想在React Native中的Text组件中插入一个新行(如\ r \ n,&lt; br /&gt;)。

如果我有:

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

34 个答案:

答案 0 :(得分:448)

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

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

答案 1 :(得分:68)

你也可以这样做:

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

我认为更容易,因为您不必在字符串中插入内容;只需将其包裹一次,就可以保留所有换行符。

答案 2 :(得分:18)

使用:

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

结果:

  

您好,

     

柯蒂斯!

答案 3 :(得分:13)

这对我有用

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

(react-native 0.41.0)

答案 4 :(得分:8)

如果你正在显示状态变量的数据,请使用它。

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

答案 5 :(得分:7)

您可以使用{'\n'}作为换行符。          嗨〜{&#39; \ n&#39;}这是测试消息。     

答案 6 :(得分:3)

您可以尝试使用

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

答案 7 :(得分: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>
  );
 }

}

答案 8 :(得分:2)

有两种选择:

选项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!

答案 9 :(得分:2)

简单使用反引号(ES 6功能)

解决方案1 ​​

const Message = 'This is a message';

<Text>
{`
  Hi~
  ${Message}
`}
</Text>

解决方案2 在文本中添加“ \ n”

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

答案 10 :(得分:2)

这样做:

<Text>

 { "Hi~ \n this is a test message." }

<Text/>

答案 11 :(得分:2)

这是一个很好的问题,你可以通过多种方式做到这一点 第一

<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> 组件中

快乐编码

答案 12 :(得分:2)

如果您从 state variable or props 获取数据,则 Text 组件有一个带有 minWidth 和 maxWidth 的样式属性。

示例

const {height,width} = Dimensions.get('screen');

const string = `This is the description coming from the state variable, It may long thank this` 

<Text style={{ maxWidth:width/2}}>{string}</Text>

这将显示屏幕宽度 50% 的文本

答案 13 :(得分:2)

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

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

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

Sublime syntax highlight

答案 14 :(得分:1)

您可以按照以下步骤进行操作:

{'创建\ n您的帐户'}

答案 15 :(得分:1)

只需将{'\n'}放在Text标签内

<Text>

   Hello {'\n'}

   World!

</Text>

答案 16 :(得分:1)

您可以像这样使用``:

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

答案 17 :(得分:1)

最干净,最灵活的方法之一就是使用Template Literals

使用此方法的一个优点是,如果要在文本正文中显示字符串变量的内容,它会更简洁明了。

(请注意反引号字符的用法)

const customMessage = 'This is a test message';
<Text>
{`
  Hi~
  ${customMessage}
`}
</Text>

会导致

Hi~
This is a test message

答案 18 :(得分:1)

https://stackoverflow.com/a/44845810/10480776 @Edison D'souza的答案正是我想要的。但是,它只是替换字符串的第一次出现。这是我处理多个<br/>标签的解决方案:

<Typography style={{ whiteSpace: "pre-line" }}>
    {shortDescription.split("<br/>").join("\n")}
</Typography>

对不起,由于声誉得分的限制,我无法评论他的帖子。

答案 19 :(得分:1)

这是使用TypeScript的React(不是React Native)解决方案。

相同的概念可以应用于React Native

import React from 'react';

type Props = {
  children: string;
  Wrapper?: any;
}

/**
 * Automatically break lines for text
 *
 * Avoids relying on <br /> for every line break
 *
 * @example
 * <Text>
 *   {`
 *     First line
 *
 *     Another line, which will respect line break
 *  `}
 * </Text>
 * @param props
 */
export const Text: React.FunctionComponent<Props> = (props) => {
  const { children, Wrapper = 'div' } = props;

  return (
    <Wrapper style={{ whiteSpace: 'pre-line' }}>
      {children}
    </Wrapper>
  );
};

export default Text;

用法:

<Text>
  {`
    This page uses server side rendering (SSR)

    Each page refresh (either SSR or CSR) queries the GraphQL API and displays products below:
  `}
</Text>

显示: enter image description here

答案 20 :(得分:0)

此代码适用于我的环境。 (反应原生 0.63.4)

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

const textWithChangeLine = "abc\ndef"

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

结果

abc
def

答案 21 :(得分:0)

有时我是这样写的:

grep

(因为我自己看起来更清楚)

答案 22 :(得分:0)

React不会喜欢您将HTML <br />放在期望的文本位置,并且\n并不总是呈现,除非在<pre>标签中。

也许将每个换行符(段落)包装在<p>标记中,如下所示:

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

如果要迭代React组件,请不要忘记key

答案 23 :(得分:0)

2021,这适用于 REACT 状态值 (您必须添加空 div,就像 return 语句一样)

this.setState({form: (<> line 1 <br /> line 2 </>) })

答案 24 :(得分:0)

为什么要这么努力?是2020年,创建一个组件来处理此类问题

    export class AppTextMultiLine extends React.PureComponent {
    render() {
    const textArray = this.props.value.split('\n');
return (
        <View>
            {textArray.map((value) => {
               return <AppText>{value}</AppText>;
            })}
        </View>
    )
}}

答案 25 :(得分:0)

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

答案 26 :(得分:0)

在数组中定义的文本行之间插入<br>的另一种方法:

import react, { Fragment } from 'react';

const lines = [
  'One line',
  'Another line',
];

const textContent =
  lines.reduce(items, line, index) => {
    if (index > 0) {
      items.push(<br key={'br-'+index}/>);
    }
    items.push(<Fragment key={'item-'+index}>{line}</Fragment>);
    return items;
  }, []);

然后可以将文本用作变量:

<Text>{textContent}</Text>

如果不可用,可以通过以下方式定义Fragment

const Fragment = (props) => props.children;

答案 27 :(得分:0)

只需在要换行的地方使用{“ \ n”}

答案 28 :(得分:0)

我正在使用React js。上述答案中没有一个对我一个人有用,但是结合起来。它可能也应该在本机上工作。下面的代码

//反应js

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

// native(未经测试,但从技术上讲应该可以使用。)

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

答案 29 :(得分:0)

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

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

答案 30 :(得分:0)

如果有人在寻找一种解决方案,而您想为数组中的每个字符串换行,则可以执行以下操作:

cache.writeData()

有关实时示例,请参见小吃:https://snack.expo.io/@cmacdonnacha/react-native-new-break-line-example

答案 31 :(得分:-1)

我使用了 p Tag 作为换行符。所以在这里我粘贴了代码。这对任何人都有帮助。

const new2DArr =  associativeArr.map((crntVal )=>{
          return <p > Id :  {crntVal.id} City Name : {crntVal.cityName} </p>;
     });

答案 32 :(得分:-3)

嘿,把它们像这样对我有用!

<块引用>
   <div>
       <p style={{ fontWeight: "bold", whitespace: "pre-wrap" }}>
         {" "}
         Hello {"\n"}
       </p>
         {"\n"}
       <p>I am here</p>
   </div>

答案 33 :(得分:-4)

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