简体   繁体   English

从父组件传递回调 function 到子组件反应

[英]Pass callback function from parent component to child component react

GOAL: Send callback function from parent to child to toggle sidebar component.目标:从父级向子级发送回调 function 以切换侧边栏组件。

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.我对status使用 true 和 false 值来打开和关闭侧边栏。

Now, in my sidebar component, I need to pass a false value to show so that is closes when my Back button is clicked.现在,在我的侧边栏组件中,我需要传递一个false值来show ,以便在单击Back按钮时关闭。

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?任何想法我做错了什么?

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:现在你正在改变一个道具,这不是你应该根据反应文档的事情,你最简单的方法是传递一个回调,它在你的侧边栏 onClick 正在执行的操作中执行相同的操作,但作为道具,并使用setStatus function,而不是手动进行更改,如下所示:

<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.您应该从父级传递回调 function 并使用 setStatus function 来执行更改。 Do not try to do the change by yourself without the setStatus function.不要尝试在没有 setStatus function 的情况下自行更改。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM