简体   繁体   中英

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?

If you are using redux(or something like that)

  • Define a variable in reducer
  • Bind mapStateToProps function to component
  • Then change that variable in reducer when you want

Read This:

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

then you can access state on any Screen of page via mapStateToProp.

But if you want to store to store theme permanently then you have to store in 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

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.

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.

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