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

React子组件接收的props显示undefined,求原因及解决方法

问题原因及解决办法

你遇到的props为undefined的原因很直接:在Parent组件渲染Child的时候,没有向Child传递任何props参数。

看你Parent组件里的这段代码:

<Child />

这里只是调用了Child组件,但没有把Parent里的category、att1等状态作为props传进去,所以Child组件的props对象自然是空的,props.category也就成了undefined。

解决步骤

1. 在Parent中传递props

修改Parent组件里的Child调用代码,把需要的状态作为props传过去:

// 把你需要传递的状态都加到Child标签上
<Child 
  category={category} 
  att1={att1} 
  set={set} 
  att1_opt={att1_opt} 
/>

2. (可选)在Child中解构props

为了代码更简洁,你可以在Child组件里直接解构props参数,这样不用每次都写props.xxx:

function Child({ category, att1, set, att1_opt }) {
    console.log("category: " + category);
    console.log("att1: " + att1);
    return <p>Please Work</p>
};

额外提示

另外,你Parent组件里的<label for="set">这类代码,在React里要把for改成htmlFor,因为for是JavaScript的保留关键字,避免控制台出现警告:

<label htmlFor="set">Set:</label>
<label htmlFor="category">Category:</label>
<label htmlFor="att1_requirement">att1:</label>

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.09 23:12:08