【发布时间】:2021-09-10 15:08:27
【问题描述】:
我已经通过 react-navigation 在我的应用中实现了主题支持,如下所示。 我正在使用系统主题设置,我的应用程序遵循此规则 这很好用,但我的待办事项清单上还剩下一件事, 在我的应用程序中切换浅色/深色主题的选项, 保留此选择,并将其存储到用户默认值或类似的东西中..
我关注了官方文档 (https://reactnavigation.org/docs/themes/) 但他们没有提到如何手动切换主题。 在我的测试中,我总是收到一条消息,主题道具是只读的,不能手动更改。 那么该怎么做呢? 任何帮助将不胜感激;)
App.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;
我真的有人可以帮助我;)
【问题讨论】:
-
您是否使用上下文或任何类型的状态管理来存储当前主题?
-
还没有,我不知道该怎么做..我只是将我的类转换为函数,我记得我以前使用过“上下文”,因为我不得不并且不能使用“ useTheme" 钩子,..我真的很好奇你的方法(y)
标签: javascript reactjs react-native react-navigation-v5