React-Native 检测屏幕缺口

React-Native Detect Screen Notch

我正在使用 nativebase.io 作为我的应用程序的 UI 框架。

我的问题

当我为 IOS 设备输入 header 时,如果 iPhone 模拟器正在模拟 iPhone X,(其中顶部有一个缺口屏幕),Header 元素会自动检测到这一点并将 Header 元素移到屏幕下方。

一些 android 设备在屏幕顶部也有类似的凹口,但是当我使用 nativebase.io Header 元素时,它没有检测到凹口和Header 与刘海重叠。

我的问题

在 react-native 或 nativebase.io 上有没有办法检测显示器是否有缺口?这样我就可以动态地偏移 Header。

由于问题出在 android,也许您应该尝试查看 StatusBar.currentHeight。由于缺口通常是状态栏的一部分,因此在 header 状态栏大小的顶部添加填充应该可以做到。

没有使用 Expo

如果您使用的是没有 Expo 的 React Native,或者已被弹出的 Expo 应用程序,您可以使用 react-native-device-info 包。它有一个 hasNotch() 功能,可以很好地检测此类设备。

Native Base ContentFooterHeader 组件检查 isIphoneX 主题变量以确定是否为设备槽口添加间距。

您可以 customized your Native Base theme 并修改您的变量文件以使用 react-native-device-info 检测缺口:

# native-base-theme/variables/*.js
import DeviceInfo from 'react-native-device-info';
...
isIphoneX = DeviceInfo.hasNotch();
...

现在,您的 Native Base HeaderFooterContent 组件应该为具有凹口的设备添加适当的间距。

使用博览会

由于 react-native-device-info 不适用于 Expo 项目,因此没有简单的方法可以做到这一点。您将必须编写一个函数来实现您的目标。如果您检查 hasNotch() source code, you will notice that the function simply does an array lookup based on the device's brand and model. You can get the device model using Expo Constants,但它们并不容易:

import { Platform } from 'react-native;
import Constants from 'expo-constants';

const getDeviceModel = () => Platform.select({
  ios: Constants.platform.ios.model,
  android: Constants.deviceName
});

但是,没有办法在 Expo 中获得设备 brand。显然,所有 ios 设备的品牌都是 Apple,但 Android 设备品牌更难以捉摸。您也许能够构造一个仅使用设备 model 的查找数组,但它可能不那么准确。

希望世博用户有更好的解决方案。

我正在使用此答案 中的方法,它对我来说工作正常。

在 React Native 中看起来像

import { StatusBar, Platform } from 'react-native';

if (Platform.OS === 'android') {
  const hasNotch = StatusBar.currentHeight > 24;
}

我一直在使用这个库"react-native-status-bar-height"并且效果很好。

https://www.npmjs.com/package/react-native-status-bar-height

安全区域视图是前往的方式。

The purpose of SafeAreaView is to render content within the safe area boundaries of a device. It is currently only applicable to iOS devices with iOS version 11 or later.

https://reactnative.dev/docs/safeareaview