You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

React Native中获取主题颜色报错:Cannot read property colors of undefined

Fixing "Cannot read property colors of undefined" When Accessing Theme Primary Color in React Native

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 theme to component props: The withTheme HOC passes the theme object as a prop to your Header component, so you need to destructure it from props.
  • Dynamic color styling: StyleSheet.create runs 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 static styles.header with an inline style that uses theme.colors.primary.
  • Wrap the component with withTheme: Make sure you export withTheme(Header) (wrapped in memo here) 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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.08 22:27:58