Site icon May's Notes

React Native Statusbar barStyle not working

React Native logo
import { StatusBar } from 'react-native'
// ...

export default function RootLayout() {
  const color = useColor()
  const { theme } = useSettingStore()
  return (
    <StatusBar
      barStyle={theme === 'dark' ? 'light-content' : 'dark-content'}
      backgroundColor={color.surfaceContainer}
    />
  )
}

原先這樣寫時預期是在亮色主題下Statusbar顯示黑字,暗色主題下Statusbar顯示白字,但會出現 Android 永遠只顯示白字,iOS永遠只顯示黑字的 bug

解決方式

監聽 theme 變化再設置 Statusbar 的 barStyle

import { useEffect } from 'react'
import { StatusBar } from 'react-native'
// ...

export default function RootLayout() {
  const color = useColor()
  const { theme } = useSettingStore()
  
  useEffect(() => {
    StatusBar.setBarStyle(theme === 'dark' ? 'light-content' : 'dark-content');
    StatusBar.setBackgroundColor(color.surfaceContainer)
  }, [theme])

  return (
    <StatusBar
      barStyle={theme === 'dark' ? 'light-content' : 'dark-content'}
      backgroundColor={color.surfaceContainer}
    />
  )
}

Exit mobile version