You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

React Native中如何根据设备主题实时修改状态栏背景?

解决React Native状态栏随系统深色/浅色模式实时更新的问题

你的代码里Appearance.getColorScheme()仅在组件首次渲染时获取一次系统颜色模式,不会监听模式变化,所以切换深色/浅色模式时组件不会重新渲染,导致状态栏样式无法实时更新。下面是两种可行的解决方法:

方法一:监听系统颜色模式变化

通过Appearance.addChangeListener监听系统模式切换,结合useState保存当前模式状态,触发组件重渲染:

import { useState, useEffect } from 'react';
import { Appearance, StatusBar } from 'react-native';
import { useTheme } from '@react-navigation/native';

const App = () => {
  const theme = useTheme();
  const [colorScheme, setColorScheme] = useState(Appearance.getColorScheme());

  useEffect(() => {
    const subscription = Appearance.addChangeListener(({ colorScheme }) => {
      setColorScheme(colorScheme);
    });

    return () => subscription.remove();
  }, []);

  const statusBarBackgroundColor = colorScheme === "dark" ? theme.colors.onSurface : theme.colors.surface;

  return (
    <StatusBar
      animated={true}
      backgroundColor={statusBarBackgroundColor}
      barStyle={colorScheme === "dark" ? "light-content" : "dark-content"}
      showHideTransition={statusBarTransition}
      hidden={hidden}
    />
  );
};

当系统颜色模式切换时,监听函数会更新colorScheme状态,触发组件重新渲染,状态栏样式就会实时同步变化。

方法二:利用React Navigation主题的自动更新

如果项目使用React Navigation,useTheme返回的主题对象自带dark属性,该属性会自动跟随系统模式变化,无需额外监听:

import { StatusBar } from 'react-native';
import { useTheme } from '@react-navigation/native';

const App = () => {
  const theme = useTheme();
  const isDarkMode = theme.dark;

  const statusBarBackgroundColor = isDarkMode ? theme.colors.onSurface : theme.colors.surface;

  return (
    <StatusBar
      animated={true}
      backgroundColor={statusBarBackgroundColor}
      barStyle={isDarkMode ? "light-content" : "dark-content"}
      showHideTransition={statusBarTransition}
      hidden={hidden}
    />
  );
};

React Navigation的主题系统会自动处理系统模式变化的监听,theme.dark实时更新后,组件会自动重渲染,状态栏样式随之更新。

内容的提问来源于stack exchange,提问作者Reza dev

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.13 12:41:14