我正在尝试使用上下文 API 更新我的 react 本机应用程序的主题,但它抛出错误 setThemeMode is not a function。(在'setThemeMode(themeMode ==='light'?'dark':'light')'中,'setThemeMode'是“i”)
我参考了以下博客文章 https://www.smashingmagazine.com/2020/01/introduction-react-context-api/
ThemeContext.js
import React from 'react';
const ThemeContext = React.createContext(['light', () => {}]);
export default ThemeContext;
应用程序.js
import React, {useState} from 'react';
import Nav from './src/navigation/Nav';
import 'react-native-gesture-handler';
import ThemeContext from './src/context/ThemeContext';
const App = () => {
const [theme] = useState("light");
return (
<>
<ThemeContext.Provider value={theme}>
<Nav />
</ThemeContext.Provider>
</>
);
};
export default App;
设置.js
import React, {useContext} from 'react';
import {View, Text, TouchableHighlight, Alert} from 'react-native';
import Icon from 'react-native-vector-icons/dist/Ionicons';
import Switches from 'react-native-switches';
import ThemeContext from './../context/ThemeContext';
import AppTheme from './../Colors';
import {
widthPercentageToDP as wp,
heightPercentageToDP as hp,
} from 'react-native-responsive-screen';
import ThemeSwitch from './ThemeSwitch';
const Settings = () => {
const [themeMode, setThemeMode] = useContext(ThemeContext);
const theme = useContext(ThemeContext);
const currentTheme = AppTheme[theme];
return (
<>
<TouchableHighlight
onPress={() => setThemeMode(themeMode === 'light' ? 'dark' : 'light')}
style={{
backgroundColor: 'black',
borderRadius: 100,
width: wp(14),
height: wp(14),
justifyContent: 'center',
alignItems: 'center',
}}>
<Icon name="md-arrow-round-back" size={wp(8)} color="white" />
</TouchableHighlight>
</>
);
};
export default Settings;
导航.js
import React from 'react';
import {NavigationContainer} from '@react-navigation/native';
import {createStackNavigator} from '@react-navigation/stack';
import Welcome from './../components/Welcome';
import Settings from './../components/Settings';
import Main from './../components/Main';
const Stack = createStackNavigator();
const Nav = () => {
return (
<NavigationContainer>
<Stack.Navigator
screenOptions={{
headerShown: false,
}}>
<Stack.Screen name="Main" component={Main} />
<Stack.Screen name="Settings" component={Settings} />
<Stack.Screen name="Welcome" component={Welcome} />
</Stack.Navigator>
</NavigationContainer>
);
};
export default Nav;
颜色.js
const AppTheme = {
light: {
name: 'light',
textColor: 'black',
backgroundColor: 'white',
},
dark: {
name: 'dark',
textColor: 'white',
backgroundColor: 'black',
},
};
export default AppTheme;
我想动态更新上下文。请原谅我这么愚蠢的错误,但我是新来的反应和 Js。我附上了问题图片。我认为我在useContext上做错了,因为当我尝试使用console.log(ThemeContext)时,它显示的是未定义而不是光。