【问题标题】:Center text vertically while occupying the whole containing view在占据整个包含视图的同时垂直居中文本
【发布时间】:2018-01-10 01:44:37
【问题描述】:

在 React Native 中,我有一个 Text 元素包含在 View 中:

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

export default class App extends Component {
  render() {
    return (
      <View style={styles.container}>
        <Text style={styles.paragraph}>
          Buy this!
        </Text>
      </View>
    );
  }
}

const styles = StyleSheet.create({
  container: {
    width: 200,
    height: 200,
    backgroundColor: '#77EB11'
  },
  paragraph: {
    backgroundColor: '#F55008',
    textAlign: 'center',
    width: '100%',
    height: '100%'
  },
});

我希望文本水平和垂直居中。通常,这可以通过在包含View 中使用justify-contentalign-items 来实现。但是,我在Windows上工作,由于this issue,我也有Text必须占据整个View的约束,否则我将无法单击整个View,当我放一个稍后在里面回调。

我还创建了一个React fiddle,但问题完全相同,但可能更容易使用。

目前,文本仅垂直居中。我怎样才能将它水平居中?

同样,最重要的约束是&lt;Text&gt; 标签应该占据所有包含&lt;View&gt; 的标签。

【问题讨论】:

  • 一种简单的方法是在文本上设置lineHeight: "200px",但这只有在您知道父容器的大小并且文本占一行时才有效。
  • 这适用于我的情况。我在 Windows 上的 React Native 中尝试过。但是,它似乎没有任何效果。除了lineHeight: "200px",还需要添加什么吗?

标签: reactjs react-native flexbox


【解决方案1】:

你可以使用

  • 容器上的display: table;
  • display: table-cell; vertical-align: middle; 在段落上。

WORKING DEMO

const styles = {
    container: {
      width: 200,
      height: 200,
      backgroundColor: '#77EB11',
      display: 'table'
    },
    paragraph: {
      backgroundColor: '#F55008',
      textAlign: 'center',
      width: '100%',
      height: '100%',
      display: 'table-cell',
      verticalAlign: 'middle'
    },
};

如果您想了解有关如何垂直对齐文本的其他策略,请尝试查看这篇文章ALIGN TEXT VERTICALLY

【讨论】:

  • 您的解决方案很棒,但是在线display: 'table-cell',我得到:Invalid value 'table-cell' for type 'Facebook.Yoga.YogaDisplay'. Parameter name: value
猜你喜欢
  • 2018-06-25
  • 1970-01-01
  • 2013-10-15
  • 2012-03-12
  • 2012-07-18
  • 1970-01-01
  • 1970-01-01
  • 2017-11-13
  • 2015-03-31
相关资源
最近更新 更多