繁体   English   中英

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

[英]Changing the theme of an app in React-Native

我正在尝试为我的应用创建主题选择器。 由于某种原因,当我启动应用程序时,最初并未设置主题,这是我认为的问题(抛出的错误是TypeError:未定义不是对象(正在评估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',
};

提前致谢!

您可以导出null对象进行更正,只需将值分配为dark, red后移动export const themes即可

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM