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

React Native + TypeScript 无法传递字符串?颜色属性传递失败求助

解决React Native组件无法接收颜色属性的问题

你的代码核心问题是props传递的结构和组件接收的结构不匹配:

在App.tsx中,你给Header组件传递的是名为colors的完整颜色对象,但Header组件里却直接尝试解构mainLight,没有从colors属性里提取值,类型定义也没对应上,导致接收不到值。

以下是两种修复方案:


方案一:保持传递完整colors对象,调整Header接收方式

修改Header.tsx的props接收逻辑,从colors属性中取出需要的颜色值:

import { Text, StyleSheet } from "react-native"
import { Colors } from '../App'

// 修正props类型:接收包含colors字段的对象
const Header = ({ colors } : { colors: Colors }) => {
    return (
        <Text style={[
            styles.appTitle,
            {
                // 从colors对象中读取mainLight
                color: colors.mainLight,
            },
        ]}>Header</Text>
    )
}

const styles = StyleSheet.create({
    appTitle: {
        fontWeight: '800',
        fontSize: 32
    },
});

export default Header

方案二:直接传递单个颜色属性(按需传递)

如果你不需要在Header里使用所有颜色,也可以直接传递需要的单个属性:

  1. 修改App.tsx的Header调用:
// 直接传递mainLight属性,不再包裹在colors里
<Header mainLight={COLORS.mainLight}/>
  1. 调整Header.tsx的类型定义(更严谨):
import { Text, StyleSheet } from "react-native"
import { Colors } from '../App'

// 用Pick类型精确指定只接收mainLight属性
const Header = ({ mainLight } : Pick<Colors, 'mainLight'>) => {
    return (
        <Text style={[
            styles.appTitle,
            {
                color: mainLight,
            },
        ]}>Header</Text>
    )
}

const styles = StyleSheet.create({
    appTitle: {
        fontWeight: '800',
        fontSize: 32
    },
});

export default Header

内容的提问来源于stack exchange,提问作者VictoriaStudios

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.09 10:15:30