字符串内的换行符(React Native)

Cal*_*alm 0 javascript react-native

我正在开发一个应用程序,在某个时候应用程序从 Facebook Graph API 接收一个字符串。

字符串看起来像这样:

"Some text some text, some text.\n\nMore text and more\n\nAnd little bit more".
Run Code Online (Sandbox Code Playgroud)

如何用换行符替换 \n\n 代码中实际有效的内容?

我知道如何用一些东西替换它:

var ret = stringToReplace.replace('\n\n','<br />');
Run Code Online (Sandbox Code Playgroud)

但是我怎样才能用工作换行符替换它。我试图用 '\n' '\r\n' 替换。每个替换都像通常的文本一样。例如:

"Some text some text, some text.<br />More text and more<br />And little bit more"
Run Code Online (Sandbox Code Playgroud)

小智 12

我知道我参加聚会已经很晚了,但我最近在\n从数据库中获取数据时遇到了同样的问题。对我有用的解决方案只是运行该replace方法并\n用 jsx替换传入\n。所以在你的情况下,它将是:

var ret = stringToReplace.replace(/\\n/g,'\n');
Run Code Online (Sandbox Code Playgroud)

看起来是一个非常愚蠢的解决方案,但它对我有用。


Vah*_*iri 6

我测试了以下代码并且它有效。您应该将文本包装在一个<Text>组件中。

export default class App extends React.Component {
  text = "Some text some text, some text.\n\nMore text and more\n\nAnd little bit more"

  render() {
    return (
      <View style={styles.container}>
        <Text>
          {this.text}
        </Text>
      </View>
    );
  }
}
Run Code Online (Sandbox Code Playgroud)

这段代码的结果是这样的: 在此处输入图片说明