React Native 在调用/共享热点时检测 IOS 状态栏高度?

React native detect IOS status bar height when calling / sharing hotspot?

在ios上调用或分享个人热点时状态栏高度发生变化,重叠视图,如何检测状态栏高度变化时?

我遇到过这个挑战,但没有找到关于 Whosebug / github 问题的答案。

我想出了自己的解决方案,post 这样可以为其他人节省一些时间。

import { NativeModules, StatusBarIOS } from 'react-native'
const { StatusBarManager } = NativeModules

componentDidMount () {
  if (Platform.OS === 'ios') {
    StatusBarManager.getHeight(response =>
        this.setState({statusBarHeight: response.height})
    )

    this.listener = StatusBarIOS.addListener('statusBarFrameWillChange',
      (statusBarData) =>
        this.setState({statusBarHeight: statusBarData.frame.height})
    )
  }
}

componentWillUnmount () {
  if (Platform.OS === 'ios' && this.listener) {
    this.listener.remove()
  }
}

工作原理

1) 获取初始高度,注意是异步方法

StatusBarManager.getHeight(response =>
    this.setState({statusBarHeight: response.height}))

2) 设置状态栏变化的监听器

StatusBarIOS.addListener('statusBarFrameWillChange',
    (statusBarData) =>
      this.setState({statusBarHeight: statusBarData.frame.height})
  )

3) 移除 componentWillUnmount 中的监听器

if (Platform.OS === 'ios' && this.listener) {
  this.listener.remove()
}

你可以使用 react-native-status-bar-height 库来获取状态栏的高度,并且可以像

marginTop: getStatusBarHeight()

或者您可以将其用作 StatusBar 的高度,如果它设置为半透明的话。

如果您使用的是 Expo

然后 import { Constants } from 'expo'

身高将是Constants.statusBarHeight

See Ref Here and here for Expo

现在 import Constants from 'expo-constants';

'expo' 更改为 'expo-constants'