React - 将道具传递给 parent
React - passing props to parent
我似乎无法让它工作。我只需要传递一个值 selectedCategory。我得到的错误:
无法读取未定义的属性(读取 'passSelectedCategory')(在 child 组件中)
Child:
const CategoryWindow =(props)=> {
const categories = ["h", "a", "s", "o"]
return (
<div className="categories-div">
{categories.map(category =>
<button className={"category-btn " + `${category}`}
key={category}
value={category}
onClick={props.passSelectedCategory(selectedCategory)} <----
>
<h2>{category}</h2>
</button>
)}
</div>
)
}
parent:
const Main =()=> {
const [showElement, setShowElement] = useState([1][0][0]);
const [selectedCategory, setSelectedCategory] = useState();
return (
<>
<main className="main">
<div>
<div>
<CategoryWindow
passSelectedCategory={setSelectedCategory} <---
/>
</div>
.....
<button className={"category-btn " + `${category}`}
key={category}
value={category}
onClick={() => props.passSelectedCategory(category)}
>
<h2>{category}</h2>
</button>
您的代码中的一切都是完美的,您只需要像我上面提到的那样更改您的 onClick 函数。
尝试将 category
作为参数传递给 props.passSelectedCategory
(子组件 CategoryWindow
没有 selectedCategory
变量的可见性)
我似乎无法让它工作。我只需要传递一个值 selectedCategory。我得到的错误:
无法读取未定义的属性(读取 'passSelectedCategory')(在 child 组件中)
Child:
const CategoryWindow =(props)=> {
const categories = ["h", "a", "s", "o"]
return (
<div className="categories-div">
{categories.map(category =>
<button className={"category-btn " + `${category}`}
key={category}
value={category}
onClick={props.passSelectedCategory(selectedCategory)} <----
>
<h2>{category}</h2>
</button>
)}
</div>
)
}
parent:
const Main =()=> {
const [showElement, setShowElement] = useState([1][0][0]);
const [selectedCategory, setSelectedCategory] = useState();
return (
<>
<main className="main">
<div>
<div>
<CategoryWindow
passSelectedCategory={setSelectedCategory} <---
/>
</div>
.....
<button className={"category-btn " + `${category}`}
key={category}
value={category}
onClick={() => props.passSelectedCategory(category)}
>
<h2>{category}</h2>
</button>
您的代码中的一切都是完美的,您只需要像我上面提到的那样更改您的 onClick 函数。
尝试将 category
作为参数传递给 props.passSelectedCategory
(子组件 CategoryWindow
没有 selectedCategory
变量的可见性)