使用 react-native-dark-mode 适配深色模式

https://www.cpming.top/p/using-react-native-dark-mode-to-detect

 

iOS 13 、 Android Q(安卓 10)和部分安卓 9 的手机都支持深色外观,苦逼的开发者又多了一项任务,App需要适配系统的浅色/暗黑2种主题,当然也可以不用适配它,强制用回原来的浅色主题。如果使用 React Native,可以引用第三方库 react-native-dark-mode 检测并适配暗黑模式。

  • useDarkMode

使用 useDarkMode,判断当前是否使用深色模式,返回是否启用深色模式,true 表示已启用。

import { useDarkMode } from 'react-native-dark-mode'

function Component() {

  const isDarkMode = useDarkMode()

  return 

}
  • useDarkModeContext

使用 useDarkModeContext,返回当前使用的模式字符串, dark 或者 light

import { useDarkModeContext } from 'react-native-dark-mode'



const backgroundColors = {

light: 'white',

dark: 'black',

}



function Component() {

const mode = useDarkModeContext()

const backgroundColor = backgroundColors[mode]

return 

}
  • DynamicStyleSheet, DynamicValue 和 useDynamicStyleSheet

就像StyleSheet一样,但是支持动态值。

import { DynamicStyleSheet, DynamicValue, useDynamicStyleSheet } from 'react-native-dark-mode'

const dynamicStyles = new DynamicStyleSheet({
	container: {
		backgroundColor: new DynamicValue('white', 'black'),
		flex: 1,
	},
	text: {
		color: new DynamicValue('black', 'white'),
		textAlign: 'center',
	},
})

function Component() {
	const styles = useDynamicStyleSheet(dynamicStyles)

	return (
		
			My text
		
	)
}
  • DarkModeProvider

允许为子组件设置特定的模式。

import { DarkModeProvider } from 'react-native-dark-mode'

function MyScreen() {
	return (
		<>
			{/* will be rendered using dark theme */}
			
				
			

			{/* will be rendered using light theme */}
			
				
			

			{/* will be rendered using current theme */}
			
		
	)
}

建议在没有模式属性的情况下将应用程序包装在DarkModeProvider中,以提高性能。

 
function App() {
	return (
		
			{/* ... */}
		
	)
}
  • useDynamicValue

根据主题返回适当的值。可以传递DynamicValue或仅传递两个参数。

import { DynamicValue, useDynamicValue } from 'react-native-dark-mode'
const lightLogo = require('./light.png')
const darkLogo = require('./dark.png')
const logoUri = new DynamicValue(lightLogo, darkLogo)

function Logo() {
	const source = useDynamicValue(logoUri)
	return 
}
import { useDynamicValue } from 'react-native-dark-mode'

function Input() {
	const placeholderColor = useDynamicValue('black', 'white')
	return 
}
  • eventEmitter

订阅模式更改的事件。

import { eventEmitter } from 'react-native-dark-mode'

eventEmitter.on('currentModeChanged', newMode => {
	console.log('Switched to', newMode, 'mode')
})
  • initialMode

这是应用程序启动的初始模式。

import { initialMode } from 'react-native-dark-mode'

console.log('App started in', initialMode, 'mode')

最后更新 2020-03-22

如若转载,请注明出处:https://www.cpming.top/p/using-react-native-dark-mode-to-detect

你可能感兴趣的:(ios深色模式适配)