Nam*_*man 0 javascript reactjs react-native react-redux react-navigation
我正在尝试设置,因此当我更改系统主题时,我的本机应用程序主题也应该更改。我使用了反应导航和反应原生外观。在应用程序启动时应用了正确的系统主题,但是当我第一次使用应用程序时更改主题时却没有。但是当我第二次尝试更改系统主题时,它也会更改应用程序主题并正常工作。
这是我的代码:-
应用程序.js
import React from 'react';
import {} from 'react-native';
import {AppearanceProvider} from 'react-native-appearance';
import Main from './main';
export default function App() {
return (
<AppearanceProvider>
<Main/>
</AppearanceProvider>
);
}
Run Code Online (Sandbox Code Playgroud)
主程序
import React, { useState,useEffect } from 'react';
import {} from 'react-native';
import {Appearance} from 'react-native-appearance';
import {DarkTheme,DefaultTheme,NavigationContainer} from '@react-navigation/native';
import Home from './home';
const myDarkTheme={
...DarkTheme,
colors:{
...DarkTheme.colors,
text:"#fff",
statusBarColor:"#000"
}
};
const myLightTheme={
...DefaultTheme,
colors:{
...DefaultTheme.colors,
text:"#000",
statusBarColor:"rgb(242, 242, 242)"
}
};
export default function Main(){
const [theme,setTheme]=useState();
console.log(theme);
const onThemeChange=()=>{
const newColor=Appearance.getColorScheme();
setTheme(newColor);
}
useEffect(()=>{
onThemeChange()
const subscription=Appearance.addChangeListener(()=>{
onThemeChange()
})
return ()=>subscription.remove();
},[])
return(
<NavigationContainer theme={theme === 'light' ? myLightTheme : myDarkTheme}>
<Home/>
</NavigationContainer>
)
}
Run Code Online (Sandbox Code Playgroud)
和 Home.js
import React from 'react';
import { StyleSheet, Text, View,StatusBar } from 'react-native';
import {useTheme} from '@react-navigation/native';
export default function Home(){
const {colors}=useTheme();
return (
<View style={{...styles.container,backgroundColor:colors.background}}>
<Text style={{color:colors.text}}>Open up App.js to start working on your app!</Text>
<StatusBar barStyle={colors.statusBarColor==='#000' ? 'light-content':'dark-content'} backgroundColor={colors.background}/>
</View>
);
}
const styles = StyleSheet.create({
container: {
flex: 1,
alignItems: 'center',
justifyContent: 'center',
},
});
Run Code Online (Sandbox Code Playgroud)
请帮助我,以便在应用程序启动后第一次更改系统主题时,主题也会第一次更改。
修改MainActivity.java
import android.content.res.Configuration; // <--- import
// copy these lines
@Override
public void onConfigurationChanged(Configuration newConfig) {
super.onConfigurationChanged(newConfig);
getReactInstanceManager().onConfigurationChanged(this, newConfig);
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
792 次 |
| 最近记录: |