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
2.6k views
in Technique[技术] by (71.8m points)

reactjs - Pass child component value back to parent component

I have a sidebar the toggles on and off. Currently, when I use the following code, the side bar opens as expected:

<Sidebar show={status} />

  <button onClick={() => setStatus((status) => !status)}>
      <SettingsIcon/>
  </button>

I use both true and false values for status to toggle the sidebar on and off.

Now, in my sidebar component, I need to pass a false value to show so that is closes when my Back button is clicked.

const Sidebar = ({ show }) => {
  const { left } = useSpring({
    from: { left: "-100%" },
    left: show ? "0" : "-100%",
  });

  return (
    <animated.div
      style={{
        left: left,
        position: "absolute",
        height: "100%",
        width: "55%",
        backgroundColor: "black",
        zIndex: 1,
      }}
      className="Sidebar"
    >
      <button onClick={() => !show}>Back</button>
      <p>hello</p>
    </animated.div>
  );
};

I can't seem to get it working. Any ideas what I am doing wrong?

question from:https://stackoverflow.com/questions/65893276/pass-child-component-value-back-to-parent-component

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

1 Answer

0 votes
by (71.8m points)

You should pass the onClick callback from parent to child and keep the show variable in the parent component.

Parent:

<Sidebar show={status} onClose={() => setShow(!show)} />
    <button onClick={() => setStatus((status) => !status)}>
        <SettingsIcon/>
    </button>
</Sidebar>

Child:

const Sidebar = ({ show, onClose }) => {
  const { left } = useSpring({
    from: { left: "-100%" },
    left: show ? "0" : "-100%",
  });

  return (
    <animated.div
      style={{
        left: left,
        position: "absolute",
        height: "100%",
        width: "55%",
        backgroundColor: "black",
        zIndex: 1,
      }}
      className="Sidebar"
    >
      <button onClick={onClose}>Back</button>
      <p>hello</p>
    </animated.div>
  );
};

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

...