在React-Native中更改应用程序的主题

时间:2018-04-16 02:11:31

标签: javascript react-native

我正在尝试为我的应用创建主题选择器。出于某种原因,当我启动应用程序时,主题最初没有设置,这是我认为的问题(错误抛出是,TypeError:undefined不是对象(评估theme.primary))。此外,当应用程序启动时,它不显示当前主题,直到单击按钮。我很反应原生,所以我确信我错过了一个简单的解决方案。

这是我的设置页面,其中有一个按钮,可以将主题从红色变为深色并返回。

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>
        );
    }
};

颜色设置文件如下,

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',
};

提前致谢!

1 个答案:

答案 0 :(得分:0)

您导出null对象,要更正它,只需在为export const themes

指定值后移动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,
};