我正在写我的第一个反应-本地应用程序,并希望像GMail一样切换主题。
事实上,当我们改变主题模式,或者在夜间设置自动黑暗主题时,GMail会变得更暗。
因此,我尝试实现Appearance.addChangeListener,就像在文档中解释的那样,但不幸的是,这个特性不起作用。
我正在试用Android 10。
如果不重新启动应用程序,,怎么能在手机主题改变时更新应用程序的颜色呢?
useEffect(() => {
dispatch(changeTheme(Appearance.getColorScheme()));
Appearance.addChangeListener(onThemeChange);
return () => Appearance.removeChangeListener(onThemeChange);
}, []);
// This function is never call
const onThemeChange = ({ colorScheme }) => {
console.log("onThemeChange", colorScheme)
dispatch(changeTheme(colorScheme));
}发布于 2021-02-06 13:59:51
通过将此代码添加到MainActivity.java中,解决了这个问题:
import android.content.res.Configuration;
@Override
public void onConfigurationChanged(Configuration newConfig) {
super.onConfigurationChanged(newConfig);
getReactInstanceManager().onConfigurationChanged(this, newConfig);
}为了测试这一特性,您可以在Android10及以上的系统中更改DarkTheme。
发布于 2021-12-31 07:47:20
useColorScheme
您可以使用useColorScheme,它将自动更新。
第一
import {useColorScheme} from 'react-native;然后,在你的功能组件中
const colorScheme = useColorScheme();我还建议编写自己的自定义钩子,以便在已更改的StatusBar和NavigationBar上更新colorScheme和NavigationBar
发布于 2022-09-08 08:37:19
使用useColorScheme
它将自动改变暗光模式。
import {useColorScheme} from 'react-native;
then,for class component
componentDidMount() {
Appearance.getColorScheme()=='dark'?this.setState({ theme: true }): this.setState({ theme: false});
}
componentDidUpdate(){
this.listener =Appearance.addChangeListener((theme) => {
// console.log("theme", theme);
theme.colorScheme == "dark"
? this.setState({ theme: true })
: this.setState({ theme: false });
});
}https://stackoverflow.com/questions/65188658
复制相似问题