【问题标题】:React Native Text component will not center inside a View componentReact Native Text 组件不会在 View 组件内居中
【发布时间】:2016-02-02 16:35:57
【问题描述】:

嗨,我认为这应该很简单,但我无法让它工作。似乎无论我做什么,我都无法让文本组件在视图内水平居中。我尝试使用 alignItems:center、justifyContent:center、alignSelf:center、textAlign:center... 没有任何效果。我可以让它垂直居中,但不能水平居中。亲爱的主,为什么?

<Animated.View style={[styles.titleContainer]}>
    <Text style={styles.title}>App logo here</Text>
</Animated.View>

如何让文本在垂直和水平方向居中?

这是我的 CSS:

titleContainer: {
    flex: 1,
    marginTop:30,
    marginBottom:30,
    justifyContent:'center'
},
title:{
    color:'white',
    textAlign:'center',
    alignSelf:'center'
},

这是我的结果:

【问题讨论】:

    标签: ios text view center react-native


    【解决方案1】:

    在主视图样式flex:1和文本集中设置textAlign:'center'

    【讨论】:

      【解决方案2】:

      使用textAlign: 'center' 属性使文本居中

      使用alignSelf:'center' 属性使视图居中

      <View style={{alignSelf:'center'}}>
      
            <Text style={{textAlign:'center'}}>I'm centered</Text>
      
      </View>
      

      【讨论】:

        【解决方案3】:

        justifyContent: 'center' 添加到容器视图。 React Native 的工作方式与 React 不同。 所以 alignItems 不起作用,而是 justifyContent 起作用。

        【讨论】:

          【解决方案4】:

          对于为最简单的情况寻找最小版本的任何人:

          <View style={styles.containerView}>
            <Text style={styles.centeredText}>I'm centered</Text>
          </View>
          
          const styles = StyleSheet.create({
            containerView: {
              justifyContent: 'center'
            }
            centeredText: {
              alignSelf: 'center'
            }
          })
          

          Align Self

          【讨论】:

            【解决方案5】:

            添加flexDirection:'column' 有助于将项目逐列居中对齐:

            titleContainer: {
                flex: 1,
                marginTop:30,
                marginBottom:30,
                justifyContent:'center',
            },
            title:{
                color:'white',
                textAlign:'center',
                alignSelf:'center',
                flexDirection: 'column'
            },
            

            【讨论】:

              【解决方案6】:

              试试这个... 这是working demo

                container: {
                  flex: 1,
                  marginTop: 30,
                  marginBottom: 30,
                  justifyContent: 'center',
                  backgroundColor: '#fff',
                },
                title: {
                  fontSize: 28,
                  textAlign: 'center',
                },
              

              【讨论】:

                猜你喜欢
                • 1970-01-01
                • 2018-08-18
                • 1970-01-01
                • 2020-09-08
                • 2023-03-21
                • 1970-01-01
                • 2018-03-14
                • 1970-01-01
                • 2023-03-29
                相关资源
                最近更新 更多