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

reactjs - Pass callback function from parent component to child component react

GOAL: Send callback function from parent to child to toggle sidebar component.

This code opens the sidebar:

<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/65895361/pass-callback-function-from-parent-component-to-child-component-react

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

1 Answer

0 votes
by (71.8m points)

Right now you're mutating a prop which is not something you should be doing according the react docs, your easiest approach will be passing a callback that does the same action in your that your sidebar onClick is doing, but as a prop, and using the setStatus function, instead of doing the change manually, something like this:

<Sidebar show={status} onSidebarClick={() => setStatus(!status)} />

And in your sidebar component you just need to do this:

const Sidebar = ({ show, onSidebarClick }) => {
  // Your code

  return (
   {/* Rest of your JSX */}
    <button onClick={onSidebarClick}>Back</button>
  )
}

You should pass the callback function from the parent and use the setStatus function to perform the change. Do not try to do the change by yourself without the setStatus function.


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

2.1m questions

2.1m answers

60 comments

57.0k users

...