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

当前回答

编辑:

如果你使用模板字面值(参见<Text>元素),你也可以像这样添加换行符:

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

export default class extends Component {

 (...)

 render(){
  return (
    <View>
      <Text>{`
        1. line 1
        2. line 2
        3. line 3
      `}</Text>
    </View>
  );
 }
}

其他回答

这段代码适用于我的环境。(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

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

< div > <p style={{fontWeight: "bold",空格:"pre-wrap"}}> {"} 你好{" \ n "} < / p > {" \ n "} <p>我在这里</p> < / div >

下面是一个使用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>

显示:

可以使用{'\n'}作为换行符。 嗨~ {'\n'}这是一个测试消息。

简单使用反勾号(es6特性)

解决方案1

const Message = 'This is a message';

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

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

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