React Native使用Appearance的useColorScheme时报Invalid hook call错误
问题原因
你遇到的报错核心原因是违反了React Hook的使用规则:只有React函数组件、命名以use开头的自定义Hook才允许在内部调用其他Hook。
你定义的Colors函数属于普通工具函数,不符合自定义Hook的命名规范,因此React会判定你在非允许的场景下调用了useColorScheme钩子,触发报错。
解决方案
第一步:调整自定义Hook命名
将你的主题工具函数重命名为以use开头的格式,示例代码如下:
import { useColorScheme } from 'react-native-appearance'; // 符合自定义Hook命名规范 export default function useColors() { // 钩子必须放在函数顶层调用 const colorScheme = useColorScheme(); const themeIndex = colorScheme === "dark" ? 1 : 0; const themes = [ { Name: "Light", Background: "f1f1f1", Foreground: "ffffff" }, { Name: "Dark", Background: "222222", Foreground: "333333" }, ]; return { Background: `#${themes[themeIndex].Background}`, Foreground: `#${themes[themeIndex].Foreground}`, }; }
注:原代码中浅色主题对应索引为0,你原来注释的逻辑中将浅色对应索引2会导致数组越界,已修正。
第二步:正确调用自定义Hook
你只能在React函数组件的顶层,或者其他自定义Hook中调用useColors,示例如下:
import useColors from './useColors'; // 函数组件中调用 export default function App() { const theme = useColors(); return ( <View style={{ flex: 1, backgroundColor: theme.Background }}> <Text style={{ color: theme.Foreground }}>主题测试</Text> </View> ); }
额外优化建议
如果你使用的是React Native 0.62及以上版本,框架已内置主题能力,不需要额外安装react-native-appearance依赖,也不需要手动包裹AppearanceProvider,直接从react-native包导入useColorScheme即可使用,可避免第三方依赖版本冲突问题。
如果修改命名后仍然报错,可执行npm ls react检查项目是否存在多份React副本,若存在多个版本可删除node_modules和 lock 文件后重新安装依赖即可。
内容的提问来源于stack exchange,提问作者Hugo Bounoua
相关产品推荐
相关产品推荐

