首页
/ Expo Material 3 Theme 使用教程

Expo Material 3 Theme 使用教程

2025-04-18 05:34:12作者:尤辰城Agatha

1. 项目介绍

expo-material3-theme 是一个开源项目,它允许开发者从 Android 12+ 设备中检索 Material 3 动态主题,并在 expo(或纯 react-native)应用中使用它。对于不兼容的设备(iOS 或旧版本的 Android),它将返回一个备用主题。

2. 项目快速启动

安装

在托管 Expo 项目中安装

此库适用于 Expo Go,但由于它需要自定义原生代码,Expo Go 不支持,因此你将无法检索系统主题(你将得到一个备用主题)。

npx expo install @pchmn/expo-material3-theme

如果你使用的是开发构建,在添加库之后,你必须重建开发客户端(仅限 Android):

npx expo prebuild --platform android
npx expo run:android

在纯 React Native 项目中安装

对于纯 React Native 项目,确保你已经安装并配置了 expo 包。

npx expo install @pchmn/expo-material3-theme
npx pod-install

使用

以下是一个基本用法示例,用于检索用户设备的 Material 3 主题(或不支持时的备用主题):

import { useMaterial3Theme } from '@pchmn/expo-material3-theme';
import { useColorScheme, View, Button } from 'react-native';

function App() {
  const colorScheme = useColorScheme();
  const { theme } = useMaterial3Theme({ fallbackSourceColor: '#6750A4' });

  return (
    <View style={{ backgroundColor: theme[colorScheme].background }}>
      <Button color={theme[colorScheme].primary}>Themed button</Button>
    </View>
  );
}

3. 应用案例和最佳实践

自定义主题

如果你想使用基于特定颜色的主题,而不是系统主题,只需向 useMaterial3Theme 钩子传递 sourceColor 参数。

// 主题将基于 #3E8260 颜色返回
const { theme } = useMaterial3Theme({ sourceColor: '#3E8260' });

更改主题

你可能还想通过生成新的主题或恢复默认主题(以使用户个性化你的应用)来更新主题。你可以使用 useMaterial3Theme 钩子来实现这一点:

const { theme, updateTheme, resetTheme } = useMaterial3Theme();

// 更新主题
<Button onPress={() => updateTheme('#3E8260')}>Update theme</Button>

// 重置主题
<Button onPress={resetTheme}>Reset theme</Button>

与 react-native-paper 一起使用

expo-material3-theme 提供了一个与 react-native-paper 兼容的主题,因此你可以轻松地结合使用这两个库。

import { useMaterial3Theme } from '@pchmn/expo-material3-theme';
import { useMemo } from 'react';
import { useColorScheme } from 'react-native';
import { Button, MD3DarkTheme, MD3LightTheme, Provider as PaperProvider } from 'react-native-paper';

function App() {
  const colorScheme = useColorScheme();
  const { theme } = useMaterial3Theme();

  const paperTheme = useMemo(() => colorScheme === 'dark'
    ? { ...MD3DarkTheme, colors: theme.dark }
    : { ...MD3LightTheme, colors: theme.light },
    [colorScheme, theme]
  );

  return (
    <PaperProvider theme={paperTheme}>
      <Button>Themed react native paper button</Button>
    </PaperProvider>
  );
}

4. 典型生态项目

在本教程中,我们没有涉及具体的生态项目,但 expo-material3-theme 可以与各种 React Native 和 Expo 相关的项目和库一起使用,以创建具有 Material 3 设计感的应用程序。你可以探索与 react-native-paperexpo 和其他 UI 组件库的集成,以构建美观且功能丰富的应用界面。

登录后查看全文
热门项目推荐