react-native - 如何修改 SafeAreaView 中的填充?

标签 react-native safeareaview

我试图将元素定位在屏幕的左上角(周围有一些边距)。由于 iPhone X 上的缺口,我使用的是 SafeAreaView。不幸的是,SafeAreaView 的填充量很大,它超出了状态栏/缺口区域。因此,应该在视觉上位于角落的元素现在比其他设备上的要低得多。

我查看了 StatusBar.currentHeight,但仅支持 Android。另一种选择是使用 https://github.com/react-native-community/react-native-safe-area-view其中有一个 forceInset范围。不幸的是,将其设置为 { top: xx } 使它像普通 View 一样工作,所有设备(也包括没有缺口的设备)都有顶部填充。

我怎么能有一个 SafeAreaView 但有一个修改过的顶部填充?

最佳答案

几个月前我遇到了类似的问题,所以我写了一个实用程序来为我提供顶部/底部 SafeArea 的正确高度,以将其作为填充添加到正常的 react-native View 中,然后通过添加/删除更多填充来使用它们。这是代码:

import { Dimensions, Platform } from 'react-native'

export function isIphoneX () {
  const iphoneXLength = 812
  const iphoneXSMaxLength = 896
  const windowDimensions = Dimensions.get('window')
  return (
    Platform.OS === 'ios' &&
    !Platform.isPad &&
    !Platform.isTVOS &&
    (windowDimensions.width === iphoneXLength ||
      windowDimensions.height === iphoneXLength ||
      windowDimensions.width === iphoneXSMaxLength ||
      windowDimensions.height === iphoneXSMaxLength)
  )
}

const DimensionsStyle = {
  safeAreaTopHeight: Platform.OS === 'ios' ? (isIphoneX() ? 44 : 20) : 0,
  safeAreaBottomHeight: Platform.OS === 'ios' && isIphoneX() ? 35 : 0,
  tabBarHeight: Platform.OS === 'ios' ? 17 : 20,
  bottomAreaHeight: Platform.OS === 'ios' && isIphoneX() ? 34 : 0
}

export default DimensionsStyle

这段代码有效是因为我们知道 iPhone X 和 iPhone XS 有一个 812p 高度,iPhone XSMax 和 XR 有 896p 高度。

然后您可以简单地将此实用程序导入您的 View 并像这样使用它:

import Dimension from '../../../utils/DimensionUtils' // path of the util
//
// rest of the code
//
const styles = StyleSheet.create({
  container: {
    paddingTop: Dimension.safeAreaTopHeight // here you can edit the height of the safeare :))
  }
})

关于react-native - 如何修改 SafeAreaView 中的填充?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57708839/

相关文章:

javascript - 通过 React Native 函数传递 Promise

reactjs - 我应该总是在 native react 中使用 safeAreaView 吗?

react-native - 标签下的 React Native Tab Bar 空白

android - 单元测试 WritableNativeMap 时出现 UnsatisfiedLinkError

react-native - Flatlist 不在绝对 View 内滚动?

react-native - SafeAreaView 的不同实现之间有什么区别?

ios - FlatList onRefresh 不适用于 SafeAreaView

swift - 使 UITableView 忽略安全区域

react-native - 使用 'Bearer' 身份验证 token 响应 native 图像

react-native - 使用分页 FlatList,如何更改可见页面上的事件?