React Native 如何为文本组件添加换行符?

1,948 阅读2分钟

这是一个简短的教程,介绍如何在React native的文本组件中添加多行。

还可以插入换行符,如\n, <br />添加到文本组件中。

在Html中,标签是用来插入换行的。

例如,如果你的多行文本显示在新的行上,我们将插入一个换行符。

我们有多种方法可以做到这一点。

让我们创建一个组件来渲染文本组件。

import * as React from 'react';
import { Text, View, StyleSheet } from 'react-native';

export default function App() {
  const Message = 'This is a message';

  return (
    
      Hello World text component
    
  );
}

React Native文本组件换行示例

第一种方法,在文本中使用\n ,使用特殊的语法。

将包含\n 的文本包裹在{}内,文本的开头和结尾都包含回车符号。

下面是一个例子

import * as React from 'react';
import { Text, View, StyleSheet } from 'react-native';

export default function App() {
  const Message = 'This is a message';

  return (
    <View>
      <Text>
      {`Hello World, \ntext component`}
      </Text>
    </View>
  );
}

这在移动设备上显示以下文字

Hello World, 
text component

同样地,你可以在{ } 内包裹多行文字,而不使用\n 符号。

import * as React from 'react';
import { Text, View, StyleSheet } from 'react-native';

export default function App() {
  const Message = 'This is a message';

  return (
    <View>
      <Text>
      {`
      Hello World,
      text component
      `}
      </Text>
    </View>
  );
}
  • 使用风格,如宽度白色空间预行

如果你的长篇内容需要将文本分成多行,可以改变宽度。

这是按屏幕分辨率变化的。

在下面的例子中,style 属性在文本组件中添加了maxWidth 参数。

文本内容被分割成多行,最大宽度为100。

import * as React from 'react';
import { Text, View, StyleSheet } from 'react-native';

export default function App() {
  const Message = 'This is a message';

  return (
    <View>
      <Text style={{ maxWidth:100}}>
   
      Hello World, text component example in react native
     
      </Text>
    </View>
  );
}

这些格式是根据屏幕分辨率自动生成的,我们无法控制何时何地中断文本。

总结

这是在react native中的一个简单例子

  • 将文本组件内容显示为多行
  • 使用样式maxWidth自动断行