簡體   English   中英

如何通過 React Native 中跨應用程序的按鈕更改主題顏色?

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

嗨,我按照此鏈接並使用上下文實現了主題更改:

如何通過 React Native 中的 Toggle 更改主題顏色?

它工作正常。 現在想使用 asyncstorage 來存儲主題顏色並在前台/componentWillMount 中的 App 上檢索它

我如何在渲染或 JSX 標簽之外的任何方法中使用 appConsumer.updateTheme(BlueGray)?

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>
    );
  }

如果您正在使用功能組件,您可以簡單地使用“useContext”掛鈎並訪問上下文。

由於您的要求是使用 componentDidMount,因此您必須使用一個類 contextType,它基本上是類中指向上下文的靜態變量。

代碼如下所示,(這是基於您提供的其他問題鏈接)

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>
        )
    }
}

這里'static context = Context;' Context 將是您創建的上下文,它應該導出並導入到此文件中,但該值將根據組件樹進行設置。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM