简体   繁体   English

根据状态React Native更改整个应用程序主题

[英]Change whole application theme based on a state React Native

I'm trying to create an application which user can change primary color and for that I've created this class 我正在尝试创建一个用户可以更改原色的应用程序,为此我创建了此类

const mode = true;

export default class Colors {
    static primary() {
        return mode ? '#fff' : '#000';
    }

    static accent() {
        return mode ? '#fff' : '#000';
    }
}

and in Components 和组件中

const styles = StyleSheet.create({
    header: {
        height: 100,
        backgroundColor: Colors.primary()
    }
});

so when user clicks on changing the theme the mode will change. 因此,当用户单击更改主题时,模式将更改。 The problem is how can I force all Components and Pages to refresh and use the new styles when the mode changes? 问题是,当mode更改时,如何强制所有组件和页面刷新并使用新样式?

If you are using redux(or something like that) 如果您正在使用redux(或类似的东西)

  • Define a variable in reducer 在reducer中定义一个变量
  • Bind mapStateToProps function to component 将mapStateToProps函数绑定到组件
  • Then change that variable in reducer when you want 然后在需要时在reducer中更改该变量

Read This: 读这个:

https://medium.com/@jonlebensold/getting-started-with-react-native-redux-2b01408c0053 https://medium.com/@jonlebensold/getting-started-with-react-native-redux-2b01408c0053

then you can access state on any Screen of page via mapStateToProp. 那么您可以通过mapStateToProp在页面的任何屏幕上访问状态。

But if you want to store to store theme permanently then you have to store in userDefault 但是,如果要永久存储主题,则必须存储在userDefault中

    import React , {PureComponent} from 'react';
    import {
      View,
      Text,
      } from 'react-native';
    import { connect } from 'react-redux';
    import { bindActionCreators } from 'redux';

    const mapStateToProps = (() => {
      return {
        colorStyle: colorTheme.style,
      };
    });

    class ColorTheme extends PureComponent {

      constructor(props) {
        super(props);
      }

      render() {
          console.log(this.props.colorStyle)
      }

    }

    export default connect(mapStateToProps, null)(ColorTheme);

I don't know if you like using global variables or not. 我不知道您是否喜欢使用全局变量。 But they can really help you here, you don't need a state. 但是他们确实可以在这里为您提供帮助,您不需要状态。 Just create some global variables in your index.js such as 只需在index.js中创建一些全局变量,例如

global.themeColorDark = "rgb(0,106,176)";
global.themeColorLight = "rgb(10,143,192)";
global.themeColorBackground = "white";

and then, you can access and edit these variables from anywhere in your app. 然后,您可以从应用程序中的任何位置访问和编辑这些变量。 without importing any file. 而不导入任何文件。

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

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