簡體   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