简体   繁体   中英

How to change theme color through a button across App in React Native?

Hi I followed this link and implemented theme change using the Context:

How to change theme color throught the Toggle in React Native?

it's working fine. now want use asyncstorage to store themecolor and retrieve it on App in the foreground/componentWillMount

how do i use appConsumer.updateTheme(BlueGray) in any method outside render or JSX tag?

render() {
    return (
      <AppConsumer>
          { appConsumer => (
      <View
        style={{
          flex: 1,
          justifyContent: 'center',
          backgroundColor: appConsumer.theme.colors.primary
        }}>
        <Button
          title="Go to two"
          onPress={() => this.props.navigation.navigate('RouteNameTwo')}
        />
        <Button onPress={ () => appConsumer.updateTheme(BlueGray) } title="Blue Gray Theme"></Button>
        <Button onPress={ () => appConsumer.updateTheme(LightGreen) } title="Light Green Theme"></Button>
      </View>
                      )}
            </AppConsumer>
    );
  }

If you are using a functional component you can simply go with the 'useContext' hook and get access to context.

As your requirement is to use componentDidMount you will have to go with a class contextType which will be basically a static variable in your class which points to the context.

The code would be like below, (This is based on the other question link that you have provided)

class ScreenComponentOne extends React.Component {
    static context = Context;
    static navigationOptions = {
        headerTitle: 'First screen',
    };

    render() {
        return (
            <View
                style={{
                    flex: 1,
                    justifyContent: 'center',
                    backgroundColor: this.context.theme.colors.primary
                }}>
                <Button
                    title="Go to two"
                    onPress={() => this.props.navigation.navigate('RouteNameTwo')}
                />
                <Button onPress={() => this.context.updateTheme(BlueGray)} title="Blue Gray Theme"></Button>
                <Button onPress={() => this.context.updateTheme(LightGreen)} title="Light Green Theme"></Button>
            </View>
        )
    }
}

here 'static context = Context;' the Context would be the context that you created, it should be exported and imported to this file, but the value would be set based on the component tree.

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