【问题标题】:Why Text element doesn't center vertically inside View?为什么文本元素不在视图内垂直居中?
【发布时间】:2020-05-10 18:28:59
【问题描述】:

使用 react-native,我创建了一个自定义按钮,如下所示:

import React, {Component, Fragment} from 'react';

import globalStyles from './../../globals/styles'

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

export default class MyButton extends Component {
    render() {
        return (
            <TouchableOpacity style={styles.opacitySurface} onPress={this.props.customAction}>
                <View style={styles.textContainer}>
                    <Text style={styles.text}>{this.props.buttonText}</Text>
                </View>
            </TouchableOpacity>
        )
    }
}

let buttonFontSize = 10;

const styles = StyleSheet.create({
        textContainer: {
            justifyContent: 'center',
            alignItems: 'center',
        },
        opacitySurface: {
            backgroundColor: globalStyles.colors.customerGreen,
            width: "25%",
            height: 60,
            padding: 10,
            borderRadius: 10,
            shadowColor: '#000',
            shadowOffset: { width: 0, height: 0 },
            shadowOpacity: 0.8,
            shadowRadius: 1.5
        },
        text: {
            textAlign: 'center',
            fontFamily: globalStyles.fonts.OpenSans,
            color: 'white',
            fontSize: buttonFontSize,
        }
    }
);

但此按钮内的文本未垂直对齐。前提:我是 react-native 的新手,我几乎可以肯定我错过了一些非常愚蠢的东西。

【问题讨论】:

  • 尝试将 style={{textAlignVertical: 'center'}} 添加到 opacitySurface 视图和 flex=1

标签: reactjs react-native text vertical-alignment


【解决方案1】:

要使justifyContentalignItems 属性起作用,它们需要位于带有display: flex 的元素上。

使您的文本居中对齐的是属性textAlign: 'center'style.text

在您的style.textContainer 上使用display: 'flex'flex: 1

textContainer: {
    display: 'flex'
    flex: 1,
    justifyContent: 'center',
    alignItems: 'center',
}

【讨论】:

【解决方案2】:

将 css 添加到您的 opacitySurface

display: "flex",
justifyContent: "center",
alignItems: "center"

它会让你的文字居中

【讨论】:

【解决方案3】:

在您的textContainer 样式中添加flex: 1

textContainer: {
    flex: 1,
    justifyContent: 'center',
    alignItems: 'center',
}

【讨论】:

    猜你喜欢
    • 2023-02-03
    • 2016-04-05
    • 1970-01-01
    • 1970-01-01
    • 2019-12-24
    • 2012-07-18
    • 2016-04-10
    相关资源
    最近更新 更多