外观
本页面由 PageTurner AI 翻译(测试版)。未经项目官方认可。 发现错误? 报告问题 →
import {Appearance} from 'react-native';
Appearance 模块用于获取用户的外观偏好信息,例如用户偏好的配色方案(浅色或深色)。
开发者说明
- Android
- iOS
- Web
The Appearance API is inspired by the Media Queries draft from the W3C. The color scheme preference is modeled after the prefers-color-scheme CSS media feature.
The color scheme preference will map to the user's Light or Dark theme preference on Android 10 (API level 29) devices and higher.
The color scheme preference will map to the user's Light or Dark Mode preference on iOS 13 devices and higher.
When taking a screenshot, by default, the color scheme may flicker between light and dark mode. It happens because the iOS takes snapshots on both color schemes and updating the user interface with color scheme is asynchronous.
示例
你可以使用 Appearance 模块判断用户是否偏好深色配色方案:
const colorScheme = Appearance.getColorScheme();
if (colorScheme === 'dark') {
// Use dark color scheme
}
虽然配色方案可立即获取,但其可能动态变化(例如在日出/日落时按计划切换)。任何依赖用户偏好配色方案的渲染逻辑或样式,都应在每次渲染时调用此函数而非缓存结果。例如,你可以使用 useColorScheme React 钩子(它提供配色方案更新订阅),或使用内联样式替代在 StyleSheet 中设置固定值。
参考
方法
getColorScheme()
static getColorScheme(): 'light' | 'dark' | null;
获取当前用户偏好的配色方案。该值后续可能更新,更新可能源于用户直接操作(如在设备设置中选择主题,或通过应用级 setColorScheme 设置界面样式),也可能按计划触发(如遵循昼夜循环的浅色/深色主题)。
支持的配色方案:
-
'light':用户偏好浅色主题 -
'dark':用户偏好深色主题 -
null:用户未指定偏好主题
另请参阅:useColorScheme 钩子
在 Chrome 中调试时,getColorScheme() 始终返回 light
setColorScheme()
static setColorScheme('light' | 'dark' | null): void;
强制应用始终采用浅色或深色界面样式。默认值 null 表示继承系统界面样式。若设置其他值,新样式将作用于应用内所有原生元素(包括警告框、选择器等)。
支持的配色方案:
-
light:应用浅色界面样式 -
dark:应用深色界面样式 -
null:遵循系统界面样式
此更改不会影响系统选定的界面样式,也不会影响其他应用中设置的样式
addChangeListener()
static addChangeListener(
listener: (preferences: {colorScheme: 'light' | 'dark' | null}) => void,
): NativeEventSubscription;
添加事件处理函数,当外观偏好发生变化时触发