首页 > 解决方案 > React-navigation 切换主题切换

问题描述

我已经使用 react-navigation 在我的应用程序中实现了主题支持,如下所示。我正在使用系统主题设置,并且我的应用程序遵循此规则,这很好用,但是我的待办事项列表上还剩下一件事,即在我的应用程序中切换浅色/深色主题的选项,保留此选择并存储它进入用户默认值或类似的东西..

我关注了官方文档(https://reactnavigation.org/docs/themes/),但他们没有提到如何手动切换主题。在我的测试中,我总是收到一条消息,主题道具是只读的,不能手动更改。那么该怎么做呢?任何帮助将不胜感激;)

应用程序.js

import { NavigationContainer } from '@react-navigation/native';
import { createStackNavigator } from '@react-navigation/stack';
import { AppearanceProvider, useColorScheme, useTheme } from 'react-native-appearance';

const Stack = createStackNavigator();

// ------------------App-----------------------------
export default function App() {

    const scheme = useColorScheme();

    const MyDarkTheme = {
    dark: true,
    ...},
    const LightTheme = {
    dark: false,
    ...}
    
    return (
      <AppearanceProvider>
        <NavigationContainer theme={scheme === "dark" ? MyDarkTheme : LightTheme}>
          <Stack.Navigator>
          <Stack.Screen>
            name="home"
          ...
          <Stack.Screen
            name="Settings"
            component={Settings}
            />
          </Stack.Navigator>
        </NavigationContainer>
      </AppearanceProvider>
    );
  }

在我的组件中:

import React, { useState, useEffect} from 'react';
import { Card } from 'react-native-elements';
import { useTheme} from '@react-navigation/native';

function CardOne(props) {

    const { colors } = useTheme(); // works
    const theme = useTheme();

return (
        <Card containerStyle={{backgroundColor: colors.cardBackgroundColor, borderColor: colors.borderColor, borderWidth: 2, borderRadius: 5}}>
        ...
        </Card>
        );
}  
export default CardOne;

我真的有人可以帮助我;)

标签: javascriptreactjsreact-nativereact-navigation-v5

解决方案


您可以使用 Context 并执行以下操作,基本上在 App.js 中保持主题状态并通过上下文更新值。

export const ThemeContext = React.createContext();

export default function App() {
  const [theme, setTheme] = useState('Light');

  const themeData = { theme, setTheme };
  return (
    <ThemeContext.Provider value={themeData}>
      <NavigationContainer theme={theme == 'Light' ? DefaultTheme : DarkTheme}>
        <Drawer.Navigator initialRouteName="Root">
          <Drawer.Screen name="Home" component={HomeScreen} />
          <Drawer.Screen name="Root" component={Root} />
        </Drawer.Navigator>
      </NavigationContainer>
    </ThemeContext.Provider>
  );
}

您可以从如下屏幕切换主题

function ProfileScreen({ navigation }) {
  const { setTheme, theme } = React.useContext(ThemeContext);
  return (
    <View style={{ flex: 1, alignItems: 'center', justifyContent: 'center' }}>
      <Text>Profile Screen</Text>
      <Button
        title="Switch Theme"
        onPress={() => setTheme(theme === 'Light' ? 'Dark' : 'Light')}
      />
    </View>
  );
}

示例代码 https://snack.expo.io/@guruparan/5b84d0


推荐阅读