I am trying to create a theme selector for my app. For some reason when I start the app the theme isn't initially set which is what I believe is the issue (error thrown is, TypeError: undefined is not an object (evaluating theme.primary)). Also when the app starts it doesnt display a current theme until after clicking the button. Im new to react-native so Im sure there is a simple solution I missed.
Here is my settings page which has a button that should change the theme from red to dark and back.
import React, { Component } from 'react';
import { StyleSheet, Text, View, Button } from 'react-native';
import styles from '../constants/Layout';
import { themes } from '../constants/Colors';
export let theme = themes.dark;
export default class SettingScreen extends Component {
constructor(props) {
super(props);
this.state = { appTheme: themes.dark };
this.changeTheme = this.changeTheme.bind(this);
}
changeTheme() {
theme = this.state.appTheme === themes.dark ? themes.red : themes.dark;
this.setState({ appTheme: theme });
}
render() {
return (
<View>
<Text style={styles.text}>
Settings{"\n"}
Current theme: {this.state.appTheme}
</Text>
<Button
onPress={this.changeTheme}
title='Change Theme'
/>
</View>
);
}
};
The color set file is as follows,
import React, { Component } from 'react';
export const themes = {
dark,
red,
};
// Dark theme
const dark = {
primary: '#424242',
primLight: '#6d6d6d',
primDark: '#1b1b1b',
text: '#ffffff',
accent: '#ff0000',
};
// Red theme
const red = {
primary: '#d32f2f',
primLight: '#ff6659',
primDark: '#9a0007',
text: '#ffffff',
accent: '#000000',
};
Thanks in advance!
You export null
object, to correct it, just move export const themes
after assign value to dark, red
import React, { Component } from 'react'; // Dark theme const dark = { primary: '#424242', primLight: '#6d6d6d', primDark: '#1b1b1b', text: '#ffffff', accent: '#ff0000', }; // Red theme const red = { primary: '#d32f2f', primLight: '#ff6659', primDark: '#9a0007', text: '#ffffff', accent: '#000000', }; export const themes = { dark, red, };
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.