【问题标题】:How can I insert a line break into a <Text> component in React Native?如何在 React Native 中的 <Text> 组件中插入换行符?
【发布时间】:2015-12-04 20:00:15
【问题描述】:

我想在 React Native 的 Text 组件中插入一个新行(如 \r\n、
)。

如果我有:

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

【问题讨论】:

  • 你可以在你想换行的地方使用\n
  • no \n 将不起作用。我用了。我建议使用 html 标签进行渲染并使用 css 或简单地

    text

    。你可以使用。

标签: javascript text react-native newline


【解决方案1】:

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

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

【讨论】:

    【解决方案2】:

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

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

    Sublime 语法高亮有助于高亮换行符:

    【讨论】:

      【解决方案3】:

      这对我有用

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

      (反应原生 0.41.0)

      【讨论】:

        【解决方案4】:

        你也可以这样做:

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

        在我看来更容易,因为您不必在字符串中插入内容;只需将其包装一次,它就会保留所有换行符。

        【讨论】:

        • 这是迄今为止最干净的解决方案,还有white-space: pre-line;
        • @Tomasz:我认为没有空格或 whiteSpace: -Stylesheet for -Tag in react-native - 还是我错了?
        • 与接受的答案相比,模板文字干净整洁
        • 我猜空白样式应该删除意图空间,对吧?如果是,我非常需要它,否则字符串文字会变得非常丑陋......
        • @Xerus 您可以使用文本后处理器来删除缩进,如下所示:gist.github.com/Venryx/84cce3413b1f7ae75b3140dd128f944c
        猜你喜欢
        • 2019-05-27
        • 2020-05-06
        • 2018-08-18
        • 2019-06-12
        • 1970-01-01
        • 2021-08-17
        • 2016-11-18
        • 1970-01-01
        • 2016-02-02
        相关资源
        最近更新 更多