我想在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>{`Hi~\nthis is a test message.`}</Text>

(react-native 0.41.0)

其他回答

这对我很有效

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

(react-native 0.41.0)

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

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

Use:

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

结果:

你好, 柯蒂斯!

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

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

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