[英]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.