首页 > 其他 > 详细

【水滴石穿】React Native 组件之SafeAreaView

时间:2019-05-21 13:06:32      阅读:286      评论:0      收藏:0      [点我收藏+]

本文转载自:https://blog.csdn.net/xiangzhihong8/article/details/80692792
SafeAreaView简介
ReactNative官方从0.50.1版本开始,加入了针对iPhone X设备齐刘海页面适配的组件SafeAreaView,为ReactNative开发APP时对iPhone X的页面适配提供了很大的方便。目前,SafeAreaView只适合iOS设备。
SafeAreaView的使用也非常简单,只需要将SafeAreaView嵌套在最根级别的视图中即可,并且在style中加上flex:1等页面样式。

<SafeAreaView style={{flex: 1, backgroundColor: '#fff'}}>
  <View style={{flex: 1}}>
    <Text>Hello World!</Text>
  </View>
</SafeAreaView>

需要注意的是,使用了RN来开发页面时,不要忘了在RN中修改相应NaviBar/TabBar的高度(如isIOS ? 64 : 42)。
技术分享图片
为了完成iPhone X的适配工作,我们还需要某些判断操作,例如下面是判断iPhone X的工具类。

import {
    PixelRatio,
    Dimensions,
    Platform
} from 'react-native';

export let screenW = Dimensions.get('window').width;
export let screenH = Dimensions.get('window').height;
// iPhoneX
const X_WIDTH = 375;
const X_HEIGHT = 812;

/**
 * 判断是否为iphoneX
 * @returns {boolean}
 */
export function isIphoneX() {
    return (
        Platform.OS === 'ios' &&
        ((screenH === X_HEIGHT && screenW === X_WIDTH) ||
            (screenH === X_WIDTH && screenW === X_HEIGHT))
    )
}

/**
 * 根据是否是iPhoneX返回不同的样式
 * @param iphoneXStyle
 * @param iosStyle
 * @param androidStyle
 * @returns {*}
 */

export function ifIphoneX(iphoneXStyle, iosStyle, androidStyle) {
    if (isIphoneX()) {
        return iphoneXStyle;
    } else if (Platform.OS === 'ios') {
        return iosStyle
    } else {
        if (androidStyle) return androidStyle;
        return iosStyle
    }
}

然后我们在适配前进行相关的判断,然后使用SafeAreaView进行适配即可。例如:

export function ifIphoneX (iphoneXStyle, regularStyle) {  
    if (isIphoneX()) {  
        return iphoneXStyle;  
    } else {  
        return regularStyle  
    }  
} 

然后根据返回的环境,添加不同的StyleSheet样式即可。

const styles = StyleSheet.create({  
    topBar: {  
        backgroundColor: '#ffffff',  
        ...ifIphoneX({  
            paddingTop: 44  
        }, {  
            paddingTop: 20  
        })  
    },  
})  

SafeAreaView的属性和View组件的属性类似,大家可以参照View的使用来给SafeAreaView进行属性设置

【水滴石穿】React Native 组件之SafeAreaView

原文:https://www.cnblogs.com/smart-girl/p/10898945.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!