React Native中获取主题颜色报错:Cannot read property colors of undefined
Got it, let's break down why you're hitting this error and how to fix it quickly.
The Root Cause
You're trying to access withTheme.colors.primary directly, but withTheme is a Higher-Order Component (HOC)—it's a function that wraps your component to inject the theme into its props, not an object with a colors property. That's why you're getting "Cannot read property colors of undefined"—you're trying to access a property on something that isn't an object.
The Fixed Code
Here's how to adjust your code to properly use the theme from withTheme:
import React, { memo } from "react"; import { StyleSheet, Text, withTheme } from "react-native"; const Header = ({ children, theme }) => ( // Merge static styles with dynamic theme color <Text style={[styles.header, { color: theme.colors.primary }]}>{children}</Text> ); const styles = StyleSheet.create({ header: { fontSize: 26, // Remove the color line here—we'll set it dynamically }, }); // Wrap your Header component with withTheme to inject the theme prop export default memo(withTheme(Header));
Key Changes Explained
- Add
themeto component props: ThewithThemeHOC passes the theme object as a prop to your Header component, so you need to destructure it from props. - Dynamic color styling:
StyleSheet.createruns once when your module loads, before the theme is injected. So we can't put the theme-dependent color there directly—instead, we merge the staticstyles.headerwith an inline style that usestheme.colors.primary. - Wrap the component with
withTheme: Make sure you exportwithTheme(Header)(wrapped inmemohere) so the theme gets injected into your component's props.
Bonus: Using Hooks (If Available)
If you're using a library like react-native-paper that provides a useTheme hook, you can also rewrite this without the HOC:
import React, { memo } from "react"; import { StyleSheet, Text } from "react-native"; import { useTheme } from "react-native-paper"; // Or your theme provider's hook const Header = ({ children }) => { const theme = useTheme(); return ( <Text style={[styles.header, { color: theme.colors.primary }]}>{children}</Text> ); }; const styles = StyleSheet.create({ header: { fontSize: 26, }, }); export default memo(Header);
Either approach will fix your error and let you access the theme's primary color correctly.
内容的提问来源于stack exchange,提问作者Joseph

