简体   繁体   English

React Native - Expo - 如何检查是否启用了暗模式?

[英]React Native - Expo - How to check if Dark mode is enabled?

I have read in the Expo/RN documentation, that for getting the system color (dark/light) we should use this API from react native.我在 Expo/RN 文档中读到过,为了获得系统颜色(深色/浅色),我们应该使用 react native 中的 这个 API

So, I have decided to create my custom hook所以,我决定创建我的自定义钩子

import { Appearance } from "react-native";

export default function useIsDarkModeEnabled() {
  return Appearance.getColorScheme() === "dark";
}

But for some reason, it is always returning me false.但出于某种原因,它总是让我返回错误。 I am testing on iOS 14, with dark theme enabled.我正在 iOS 14 上进行测试,启用了深色主题。

Any ideas?有任何想法吗?

Whenever I check the current appearance of the device I use the useColorScheme() function, not getColorScheme().每当我检查设备的当前外观时,我都会使用 useColorScheme() 函数,而不是 getColorScheme()。

You can use Context to persist it throughout the application, or put it at the root of your app and pass it down to your components as props (not the best).你可以使用 Context 在整个应用程序中持久化它,或者把它放在你的应用程序的根目录,然后将它作为 props 传递给你的组件(不是最好的)。 To persist the theme, you can use AsyncStorage to store the last state of the appearance.为了保持主题,您可以使用 AsyncStorage 来存储外观的最后状态。

Then whenever the application opens, it will pull that last state unless the device has changed its appearance since then.然后每当应用程序打开时,它将拉取最后一个状态,除非设备从那时起改变了它的外观。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM