如果你的 React Native 版本較新,它提供一個主題API useColorScheme,你可以直接使用它。如果不是,需安裝額外的庫,如react-native-appearance。
下面是一個使用 react-native-appearance(或 useColorScheme)的簡單示例:
使用 react-native-appearance
需要安裝 react-native-appearance(如果它還不是 React Native 的一部分)。
npm install react-native-appearance
# 或者
yarn add react-native-appearance
然后,你可以在你的組件中使用它:
import React, { useEffect, useState } from 'react';
import { Text, View } from 'react-native';
import { useColorScheme } from 'react-native-appearance'; const DynamicThemeComponent = () => { // 使用 useColorScheme Hook 獲取當前顏色方案 const colorScheme = useColorScheme(); // 根據顏色方案設置主題 const theme = colorScheme === 'dark' ? 'darkTheme' : 'lightTheme'; // 這里可以根據 theme 變量來設置組件的樣式 // 但為了簡化示例,我們直接在文本中顯示當前的顏色方案 return ( <View> <Text>當前顏色方案: {colorScheme}</Text> {/* 這里可以添加更多的組件,并使用 theme 變量來設置它們的樣式 */} </View> );
}; export default DynamicThemeComponent;
使用 useColorScheme(內置于 React Native)
如果你的 React Native 版本較新,并且 useColorScheme 已經內置,你可以直接使用它,而無需安裝額外的庫:
import React from 'react';
import { Text, View, useColorScheme } from 'react-native'; const DynamicThemeComponent = () => { // 使用 useColorScheme Hook 獲取當前顏色方案 const colorScheme = useColorScheme(); // 根據顏色方案設置組件的樣式 const textColor = colorScheme === 'dark' ? 'white' : 'black'; const backgroundColor = colorScheme === 'dark' ? 'black' : 'white'; return ( <View style={{ backgroundColor }}> <Text style={{ color: textColor }}>當前顏色方案: {colorScheme}</Text> {/* 其他組件 */} </View> );
}; export default DynamicThemeComponent;