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

React父组件向子组件传常量遇undefined问题求助

问题原因

你在父组件中传递数据时,将PIinput对象包装在了名为props的属性里,导致子组件接收的props对象结构是{ props: PIinput },直接访问props.label自然会返回undefined——因为这些属性实际嵌套在props.props层级下。

解决方案

推荐两种修复方式:

方式一:展开传递属性(更符合React常规写法)

修改父组件中Card组件的调用,使用对象展开语法把PIinput的属性直接作为独立props传递:

// App组件中
<Card {...PIinput} />

这样子组件里的props就直接包含label和inputs属性,原代码可以正常使用:

export function Card(props) {
    console.log(props, props.label);
    return (
        <div className='card'>
            <h2>{props.label}</h2>
            <form>
                {props.inputs.map((item) => {
                    return <h3>{item}</h3>;
                })}
            </form>
        </div>
    );
}

方式二:在子组件中访问嵌套的props

如果不想修改父组件的传递方式,子组件里需要调整访问路径,从props.props下读取属性:

export function Card(props) {
    console.log(props.props, props.props.label);
    return (
        <div className='card'>
            <h2>{props.props.label}</h2>
            <form>
                {props.props.inputs.map((item) => {
                    return <h3>{item}</h3>;
                })}
            </form>
        </div>
    );
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.02 14:13:14