React Native Appearance 项目教程
1. 项目介绍
react-native-appearance
是一个用于访问操作系统外观信息的 React Native 库,目前主要支持检测用户的首选颜色方案(如浅色模式和深色模式)。该库适用于 iOS、Android 和 Web 平台。
该项目最初由 Facebook 开发,旨在为 React Native 核心提供外观信息的支持。然而,随着 React Native 核心的更新,该库已被归档,推荐使用 React Native 核心中的 Appearance
模块。
2. 项目快速启动
安装
使用 Expo 管理项目
-
安装
react-native-appearance
:expo install react-native-appearance
-
在
app.json
中配置userInterfaceStyle
:{ "expo": { "userInterfaceStyle": "automatic" } }
使用裸 React Native 项目
-
安装
react-native-appearance
:yarn add react-native-appearance
-
链接库:
react-native link react-native-appearance
配置
iOS 配置
在 Info.plist
中添加 UIUserInterfaceStyle
键:
<key>UIUserInterfaceStyle</key>
<string>Automatic</string>
Android 配置
在 AndroidManifest.xml
中添加 uiMode
标志:
<activity android:configChanges="keyboard|keyboardHidden|orientation|screenSize|uiMode">
使用示例
import React from 'react';
import { AppearanceProvider, useColorScheme } from 'react-native-appearance';
import { View, Text } from 'react-native';
const App = () => {
const colorScheme = useColorScheme();
return (
<AppearanceProvider>
<View style={{ flex: 1, justifyContent: 'center', alignItems: 'center' }}>
<Text>当前颜色方案: {colorScheme}</Text>
</View>
</AppearanceProvider>
);
};
export default App;
3. 应用案例和最佳实践
应用案例
- 动态主题切换:根据用户的系统设置自动切换应用的主题(浅色或深色)。
- 自定义主题:允许用户在应用内手动选择主题,并根据选择动态调整 UI。
最佳实践
- 使用
AppearanceProvider
:确保在应用的根组件中使用AppearanceProvider
,以便在整个应用中访问外观信息。 - 订阅颜色方案变化:使用
Appearance.addChangeListener
订阅颜色方案的变化,以便在用户更改系统设置时动态更新 UI。
4. 典型生态项目
- React Navigation:结合
react-native-appearance
实现动态导航栏主题切换。 - React Native Paper:使用
react-native-appearance
实现 Material Design 组件的动态主题切换。 - Expo:Expo SDK 35+ 支持
react-native-appearance
,允许 Expo 应用根据系统设置自动切换主题。
通过以上步骤,您可以轻松地在 React Native 项目中集成 react-native-appearance
,并根据用户的系统设置动态调整应用的外观。