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 } }