繁体   English   中英

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

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

我正在尝试创建一个用户可以更改原色的应用程序,为此我创建了此类

const mode = true;

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

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

和组件中

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

因此,当用户单击更改主题时,模式将更改。 问题是,当mode更改时,如何强制所有组件和页面刷新并使用新样式?

如果您正在使用redux(或类似的东西)

  • 在reducer中定义一个变量
  • 将mapStateToProps函数绑定到组件
  • 然后在需要时在reducer中更改该变量

读这个:

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

那么您可以通过mapStateToProp在页面的任何屏幕上访问状态。

但是,如果要永久存储主题,则必须存储在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);

我不知道您是否喜欢使用全局变量。 但是他们确实可以在这里为您提供帮助,您不需要状态。 只需在index.js中创建一些全局变量,例如

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

然后,您可以从应用程序中的任何位置访问和编辑这些变量。 而不导入任何文件。

暂无
暂无

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

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