我正在尝试使用上下文API更新我的react native应用程序的主题,但是它抛出错误setThemeMode不是一个函数。 (在'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;
App.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;
Settings.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;
Nav.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;
Colors.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)时,它显示的是 undefined 而不是光。
答案 0 :(得分:0)
const [themeMode, setThemeMode] = useContext(ThemeContext);
应该是
const [themeMode, setThemeMode] = useState(ThemeContext);