I want to pass the setter of a React Hook to a Child Component. So that a button in the child component updates the state via setter which is saved in the Parent Component. I tried following setup but I get an error message :
TypeError: setshowOptionPC is not a function
onClick
Is my approach even possible? And if not how could I possibly do that structure using a React Hook.
Below a simplified version of my code:
import React, { useState } from "react";
function ChildComponent({ setshowChildOptionBC, setshowChildOptionPC }) (
<div>
<button
onClick={() => {
setshowChildOptionPC(false);
setshowChildOptionBC(true);
}}
>
BC
</button>
<button
onClick={() => {
setshowChildOptionPC(true);
setshowChildOptionBC(false);
}}
>
PC
</button>
</div>
);
function ParentComponent() {
const [showOptionBC, setshowOptionBC] = useState(true);
const [showOptionPC, setshowOptionPC] = useState(false);
return (
<div>
<ChildComponent
setshowChildOptionBC={setshowOptionBC}
setshowChildOptionPC={setshowOptionPC}
/>
{showOptionBC && <div>BC</div>}
{showOptionPC && <div>PC</div>}
</div>
);
}
export default ParentComponent;
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…