javascript - 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;
我真的有人可以帮助我;)
解决方案
您可以使用 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>
);
}
推荐阅读
- javascript - 弹出模式时如何保持文本被选中/突出显示
- javascript - FullCalendar - 内联可滚动日历
- react-native - 水平平面列表重新渲染更改 ListHeaderComponent
- android - 如何调试第三方flutter插件
- pytorch - PyTorch 中如何实现 Conv2d 的算法
- mysql - 通过迁移向导将 QODBC 连接到 MySQL 时出错
- android - 安排稍后执行的任务(时间+日期)android
- html - 如何使用简单的 HTML 表单将指标发布到 InfluxDB?
- c++ - OpenGL 纹理被镜像
- html - 概述 DIV 和图像