SafeAreaView
的目的是在一个“安全”的可视区域内渲染内容。具体来讲就是由于目前有 iPhone X 这样的带有“刘海”的全面屏设备,因此须要避免内容渲染到不可见的“刘海”范围内。本组件目前仅支持 iOS 设备以及 iOS 11 或更高版本。react
SafeAreaView
会自动根据系统的各类导航栏、工具栏等预留出空间来渲染内部内容。更重要的是,它还会考虑到设备屏幕的局限,好比屏幕四周的圆角或是顶部中间不可显示的“刘海”区域。android
实例代码:ios
import { // … SafeAreaView } from 'react-native'; class Main extends React.Component { render() { return ( <SafeAreaView style={styles.safeArea}> <App /> </SafeAreaView> ) } } const styles = StyleSheet.create({ // …, safeArea: { flex: 1, backgroundColor: '#ddd' } })
一般在开发过程当中,为了适配IPhonX设备,须要开发者本身来作代码操做。例以下面是判断iPhone X的工具类。react-native
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进行适配便可。例如:安全
/** * 根据是不是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 } }