Bug in `react-native`

https://github.com/expo/expo/issues/10815
This commit is contained in:
Zhiyuan Zheng 2021-01-02 17:55:08 +01:00
parent ea465c828a
commit 5a80359739
No known key found for this signature in database
GPG Key ID: 078A93AB607D85E0
1 changed files with 29 additions and 2 deletions

View File

@ -1,8 +1,9 @@
import React, { createContext, useContext, useEffect, useState } from 'react' import React, { createContext, useContext, useEffect, useState } from 'react'
import { useColorScheme } from 'react-native' import { Appearance } from 'react-native'
import { useSelector } from 'react-redux' import { useSelector } from 'react-redux'
import { ColorDefinitions, getTheme } from '@utils/styles/themes' import { ColorDefinitions, getTheme } from '@utils/styles/themes'
import { getSettingsTheme } from '@utils/slices/settingsSlice' import { getSettingsTheme } from '@utils/slices/settingsSlice'
import { throttle } from 'lodash'
type ContextType = { type ContextType = {
mode: 'light' | 'dark' mode: 'light' | 'dark'
@ -18,8 +19,34 @@ export const ManageThemeContext = createContext<ContextType>({
export const useTheme = () => useContext(ManageThemeContext) export const useTheme = () => useContext(ManageThemeContext)
const useColorSchemeDelay = (delay = 250) => {
const [colorScheme, setColorScheme] = React.useState(
Appearance.getColorScheme()
)
const onColorSchemeChange = React.useCallback(
throttle(
({ colorScheme }) => {
setColorScheme(colorScheme)
},
delay,
{
leading: false
}
),
[]
)
React.useEffect(() => {
Appearance.addChangeListener(onColorSchemeChange)
return () => {
onColorSchemeChange.cancel()
Appearance.removeChangeListener(onColorSchemeChange)
}
}, [])
return colorScheme
}
const ThemeManager: React.FC = ({ children }) => { const ThemeManager: React.FC = ({ children }) => {
const osTheme = useColorScheme() const osTheme = useColorSchemeDelay()
const userTheme = useSelector(getSettingsTheme) const userTheme = useSelector(getSettingsTheme)
const currentMode = const currentMode =
userTheme === 'auto' ? (osTheme as 'light' | 'dark') : userTheme userTheme === 'auto' ? (osTheme as 'light' | 'dark') : userTheme