RN端ios全面屏刘海适配

2022-07-25,,

  • 项目中引入以下组件SafeAreaViewPlus.js 。可以自定义顶部和底部颜色。
    注意: 如果有用到 native-base 提供的Header组件,下面文件中topArea的样式需改为height: 24, 如果没有用到,height:44
/**
* iPhone适配全面屏(iPhoneX)
*/

import React, {Component,} from 'react';
import {DeviceInfo, SafeAreaView, StyleSheet, View, ViewPropTypes} from 'react-native';
import {PropTypes} from 'prop-types';

export default class SafeAreaViewPlus extends Component {
 static propTypes = {
   ...ViewPropTypes,
   topColor: PropTypes.string,     //顶部刘海适配区域颜色
   bottomColor: PropTypes.string,  //底部刘海适配区域颜色
   enablePlus: PropTypes.bool,     //是否使用此组件,如果不使用,则会用rn自带的SafeAreaView
   topInset: PropTypes.bool,       //顶部是否需要适配全面屏
   bottomInset: PropTypes.bool,    //底部是否需要适配全面屏

 };
 static defaultProps = {
   topColor: 'transparent',
   bottomColor: '#f8f8f8',
   enablePlus: true,
   topInset: true,
   bottomInset: false,
 };

 genSafeAreaViewPlus() {
   //外部控件包含一些控件,那么外面控件的children就是它包含的这些控件
   const {children, topColor, bottomColor, topInset, bottomInset} = this.props;
   return <View style={[styles.container, this.props.style]}>
     {this.getTopArea(topColor, topInset)}
     {children}
     {this.getBottomArea(bottomColor, bottomInset)}
   </View>;
 }

 genSafeAreaView() {
   return <SafeAreaView style={[styles.container, this.props.style]} {...this.props}>
     {this.props.children}
   </SafeAreaView>
 }

 getTopArea(topColor, topInset) {
   return  !DeviceInfo.isIPhoneX_deprecated || !topInset ? null
     : <View style={[styles.topArea, {backgroundColor: topColor}]}/>;
 }

 getBottomArea(bottomColor, bottomInset) {
   return  !DeviceInfo.isIPhoneX_deprecated || !bottomInset ? null
     : <View style={[styles.bottomArea, {backgroundColor: bottomColor}]}/>;
 }

 render() {
   const {enablePlus} = this.props;
   return enablePlus ? this.genSafeAreaViewPlus() : this.genSafeAreaView();
 }
}


const styles = StyleSheet.create({
 container: {
   flex: 1,
 },
 topArea: {
   height: 44,//如果有用到 native-base 提供的Header组件, height: 24, 如果没有用到,height:44
 },
 bottomArea: {
   height: 34,
 }
});
  • 参数说明
参数 默认值 说明
topColor ‘transparent’ 顶部刘海适配区域颜色
bottomColor ‘#f8f8f8’ 底部刘海适配区域颜色
enablePlus true 是否使用此组件,如果不使用,则会用rn自带的SafeAreaView
topInset true 顶部是否需要适配全面屏
bottomInset false 底部是否需要适配全面屏
  • 使用方法

本文地址:https://blog.csdn.net/weixin_37221852/article/details/112858253

《RN端ios全面屏刘海适配.doc》

下载本文的Word格式文档,以方便收藏与打印。