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
相关产品推荐
相关产品推荐

