zoukankan      html  css  js  c++  java
  • React Native 实现垂直水平居中(justifyContent、alignItems)

    项目中我们经常会遇到子组件和父组件垂直水平居中的问题,那么我们如何实现这个效果呢?

    方法有很多种,下面以自定义按钮为例简述下实现方法,

    A:主要使用这个来实现(相当于水平垂直居中):

    justifyContent: 'center',
         alignItems:'center',

    首先要理解justifyContent、alignItems两个布局属性,详情参考: React Native 布局 justifyContent、alignItems、alignSelf、alignContent

    type FlexAlignType = "flex-start" | "flex-end" | "center" | "stretch" | "baseline";
    justifyContent?: "flex-start" | "flex-end" | "center" | "space-between" | "space-around" | "space-evenly";
    alignItems?: FlexAlignType;

    效果如图所示:

     

    代码如下:

                   <View style={style.btn_bg}>
                        <TouchableOpacity onPress={() => {
    
    
                        }}>
                            <View style={style.btn_blue}>
                                <Text style={style.btn}>测试一下下</Text>
                            </View>
                        </TouchableOpacity>
                    </View>
    
    
       btn_bg: {
            backgroundColor: 'yellow',
            paddingHorizontal: 15,
            paddingVertical: 8,
        },
    
        btn_blue: {
            backgroundColor: '#3480FF',
            height: 40,
            borderRadius: 20,
            justifyContent: 'center',
            alignItems:'center',
        },
    
        btn: {
            fontSize: DeviceHelp.fontSize(16),
            color: '#FFFFFF',
            backgroundColor: 'red'
        },

    B:当子控件是Text时也可以使用textAlign:'center'方式来实现(这种方式就是要求文本没有背景色才可以达到上述效果,算是取巧),

    父控件:justifyContent: 'center',

    子控件:textAlign:'center'

    效果如图:

    变动代码:

    btn_blue: {
            backgroundColor: '#3480FF',
            height: 40,
            borderRadius: 20,
            justifyContent: 'center',
        },
    
        btn: {
            fontSize: DeviceHelp.fontSize(16),
            color: '#FFFFFF',
            backgroundColor: 'red',
            textAlign:'center'
        },

    综上所述:

    最好的方案就是A,当子控件是Text时,可以考虑B方案。

  • 相关阅读:
    android studio 使用(一)
    【转】How to Change File Ownership & Groups in Linux
    ubuntu 14.04安装nodejs
    基于源码学习-fighting
    linux shell操作
    linux用户管理
    ubutu强制结束进程 kill -9 ProcessID
    ubuntu 添加和删除用户
    ubuntu 14.04查看java的安装路径
    vuex 中关于 mapState 的作用
  • 原文地址:https://www.cnblogs.com/lijianyi/p/14894609.html
Copyright © 2011-2022 走看看