【问题标题】:How to Horizontally Center React Native Flexbox Text that Wraps across Multiple Lines如何将跨多行的 React Native Flexbox 文本水平居中
【发布时间】:2018-10-01 15:22:12
【问题描述】:

在 React Native 中,使用 flexbox,我的 <Text> 组件中的文本水平(和垂直)居中。

这按预期工作 - if 文本行足够短,它确实不需要需要换行 到下一行。

但是,当给定一个 长文本 字符串时,该字符串换行 跨越多行,呈现的文本不会水平居中
而是将换行的文本与左边缘对齐。

如何强制换行的文本水平居中?

这水平居中shortText,但不是longText

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

class Deck extends React.Component {

  render() {
    const shortText = 'Centered!';  
    const shortText = 'This very long line of text does NOT Center. Instead the wrapped text is aligned to the left edge of the container.';         

    return (
      <View style={styles.container}>
        <View>
          <Text style={styles.titleText}> {shortText} </Text>
          <Text style={styles.titleText}> {longText}  </Text>
        </View>   
      </View>
    );
  }
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
    alignItems: 'center',
    justifyContent: 'center',
  },
  titleText: {
    fontSize: 27,
    flexWrap: 'wrap', 
    alignSelf: 'center',
  },
});    

注意:我发现 大量 Stack Overflow 问题/答案和博客文章
垂直居中,水平在文本不换行到多条“行”时居中。
但我一直无法找到任何用于居中的换行为多行的水平文本

另外:请注意,React Native 实现了 "limited style inheritance" for text,这与 css 标准略有不同。例如,&lt;Text&gt;inherits color 和 'fontSizeproperties only from parentTextcomponents, but notView` 组件。
此外,React Native 的 Flexbox layout 实现与 CSS 标准略有不同。
我不知道 React Native 的差异是否也会影响水平居中的换行文本。

【问题讨论】:

  • textAlign: "center" 添加到&lt;Text&gt; 的样式道具是否有效?

标签: javascript css react-native flexbox


【解决方案1】:

您可以像这样设置textAlign 属性:

<Text style={{textAlign: 'center'}}>centered Text</Text>

您可以在此处查看 textAlign 属性的文档: https://reactnative.dev/docs/text-style-props#textalign

【讨论】:

  • @SherylHohman 好的,现在我看到您已经更新了代码。 justifyContent: 'center' 呢?
  • 文档移动了,我建议对您的答案进行编辑以修复它们,但您的答案正确并为我工作。谢谢!
猜你喜欢
  • 2016-08-06
  • 2020-12-09
  • 1970-01-01
  • 1970-01-01
  • 2017-03-26
  • 2018-12-01
  • 2018-09-23
  • 1970-01-01
  • 2016-09-16
相关资源
最近更新 更多