Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
330 views
in Technique[技术] by (71.8m points)

javascript - How to pass a React Hook to a child component

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

I think you just forgot to destructure props in your child component. This might help.

function ChildComponent({setshowOptionBC, setshowOptionPC}) {..

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...