【问题标题】:How can i get the right ColorScheme in react-native?如何在 react-native 中获得正确的 ColorScheme?
【发布时间】:2021-06-29 09:58:32
【问题描述】:

我在使用 Expo CLI 创建的新 react-native 应用程序中使用自定义挂钩来支持带有 tailwindcss 的暗模式。带有暗模式逻辑的 TailwindProvider 如下所示:

const TailwindProvider: React.FC = ({ children }) => {
  const [currentColorScheme, setcurrentColorScheme] = useState(Appearance.getColorScheme());
  console.log("CurrentColorScheme:", currentColorScheme);
  const isDarkMode = currentColorScheme == "dark";
  const tw = (classes: string) => tailwind(handleThemeClasses(classes, isDarkMode))
  return <TailwindContext.Provider value={{ currentColorScheme, setcurrentColorScheme, tw, isDarkMode }}>{children}</TailwindContext.Provider>;
}

如您所见,我使用react-native 中的Appearance.getColorScheme() 方法来获取当前的ColorScheme。但在 iOS 和 Android 上,无论是在调试模式还是在生产模式下,我总是得到 light 而不是 dark

我该如何解决这个问题?

【问题讨论】:

    标签: react-native expo darkmode


    【解决方案1】:

    据说在调试和生产代码中都会返回“light”。但是,仅返回“light”的一个可能原因是是否使用了 Chrome 调试。 根据文档页面:[https://reactnative.dev/docs/appearance][1]

    “注意:使用 Chrome 进行调试时,getColorScheme() 将始终返回光。”

    如果使用,这也适用于 useColorScheme() 钩子。

    另外,如果有 App.json,iOS 和 Android 的 userInterfaceStyle 都应该设置为自动。

    【讨论】:

      【解决方案2】:

      useState(Appearance.getColorScheme()) 的问题是它只会在应用加载时检查一次。您可以尝试useColorScheme() 挂钩以保持最新状态:

      // ...
      import { useColorScheme } from 'react-native';
      
      const TailwindProvider: React.FC = ({ children }) => {
        const currentColorScheme = useColorScheme();
        console.log({ currentColorScheme });
        const isDarkMode = currentColorScheme === "dark";
        const tw = (classes: string) => tailwind(handleThemeClasses(classes, isDarkMode));
        return <TailwindContext.Provider value={{ currentColorScheme, tw, isDarkMode }}>{children}</TailwindContext.Provider>;
      }
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2017-02-01
        • 2021-10-01
        • 2018-03-25
        • 2018-03-17
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多