我是 React 新手,几天来一直在解决这个问题。基本上我有一个应用程序组件、父组件和子组件。我的问题是我试图将道具从父级传递给子级,但我尝试根据控制台日志传递的每个道具都未定义。为什么我无法检索任何道具的正确价值,有什么想法吗?预先感谢!
下面是我的父组件的示例:
import { useState } from "react";
import Child from "./Child";
function Parent() {
const sets = [
{
name: "Set1",
categories: [
{
name: "Cat1",
att1_opt: ["A", "B", "C"],
att2_opt: [null],
att3_opt: ["1", "2", "3"]
},
{
name: "Cat2",
att1_opt: ["A", "D"],
att2_opt: ["AA", "BB", "CC"],
att3_opt: ["4", "5"]
},
{
name: "Cat3",
att1_opt: [null],
att2_opt: [null],
att3_opt: ["6"]
},
],
}
];
const [set, setSet] = useState('--Set--');
const [category, setCategory] = useState('--Category--');
const [att1, setAtt1] = useState('--att1--');
const [categories, setcategories] = useState([]);
const [att1_opt, setAtt1_opt] = useState([]);
const changeSet = (event) => {
setSet(event.target.value);
if (event.target.value !== '--Set--') {
setcategories(sets.find(cat => cat.name === event.target.value).categories);
}
};
const changeCategory = (event) => {
setCategory(event.target.value);
if (event.target.value !== '--Category--') {
setAtt1_opt(categories.find(category => category.name === event.target.value).att1_opt);
}
};
const changeatt1 = (event) => {
setAtt1(event.target.value);
};
return (
<>
<div>
<div>
<form>
<div>
<label for="set">Set:</label>
<select value={set} onChange={changeSet}>
<option>--Set--</option>
{sets.map(cat => (
<option value={cat.name}>{cat.name}</option>
))}
</select>
<br />
</div>
<div><label for="category">Category:</label>
<select value={category} onChange={changeCategory}>
<option>--Category--</option>
{categories.map((category) => (
<option value={category.name}>{category.name}</option>
))}
</select>
<br />
</div>
<div>
<label for="att1_requirement">att1:</label>
<select value={att1} onChange={changeatt1}>
<option>--att1--</option>
{att1_opt.map(att1 => (
<option value={att1}>{att1}</option>
))}
</select>
<br />
</div>
<Child />
</form>
</div>
</div >
</>
);
}
export default Parent;
这是子组件:
import { useState } from "react";
function Child(props) {
console.log("props " + props.category)
return <p>Please Work</p>
};
export default Child;
您需要明确传递您希望孩子拥有的每个道具。我假设您希望父级的
category
状态成为子级的 category
属性:
<Child
category={ category }
/>
在这种情况下,程序员的意图可能看起来“显而易见”,因为 prop 和变量共享相同的名称,但情况并非总是如此,而且可能性很大,所以 React 不会为你假设这一点。
作为提示,您可以在孩子身上解构道具,这可能会更清楚孩子期望的道具范围:
function Child({
category,
anotherProp,
isExampleProp = true //etc
}) {