问题
In some very specific cases I need to set the height of a View to the full height of the device useful area (without using flex).
I was using a hardcoded "notch height" to calculate this useful height but I just discovered that the notch can have different heights depending on the device. (3 points of difference between iPhone XS and iPhone XS Max).
Is there a way to know the useful height of a device with notch and safe area?
回答1:
You can use the react-native-safe-area. it provides function to Get safe area inset top, bottom, left, right.
import SafeArea, { type SafeAreaInsets } from 'react-native-safe-area'
//Retrieve safe area insets for root view
SafeArea.getSafeAreaInsetsForRootView()
.then((result) => {
console.log(result)
// { safeAreaInsets: { top: 44, left: 0, bottom: 34, right: 0 } }
})
回答2:
As @mohammed-ashfaq said, react-native-safe-area solves the problem. However, it returns the insets with a promise and I needed those values statically.
Given that, I created react-native-static-safe-area-insets that enables access to the insets values as constants.
回答3:
You can get the screen, which users phone, width and height from Dimensions component.
import { Dimensions } from 'react-native'
const { width, height } = Dimensions.get('window'); // if you use the width you can get the screen width by pixels. And also height is the height pixels of the phone.
const screenWidthSomePart = width * 0,6 // Some times you can get the percentage of the screen so you can use this. screen %60
If you wanna see the safe are for the Iphone X. You can use the SafeAreaView Componenet
import { SafeAreaView } from 'react-native'
return(
<SafeAreaView>
..... // your screen componenet
</SafeAreaView>
);
回答4:
Use Dimension module from 'react-native' like there :
import { Dimensions, Platform, StatusBar } from 'react-native'
const windowHeight = Dimensions.get('window').height
const screenHeight = Dimensions.get('screen').height
来源:https://stackoverflow.com/questions/53319968/how-to-know-the-useful-height-of-an-ios-device-in-react-native