繁体   English   中英

在 React && styled-components 中使用 State 从两个不同的按钮触发侧边栏

[英]Trigger Sidebar from two different button using State in React && styled-components

第一个按钮:

const [open, setOpen] = useState(false);
  return (
    <>
      <SideCart open={open} />
      <CartButton open={open} onClick={() => setOpen(!open)}>
      )
    </>

侧边栏:

const [hide, setHide] = useState(open ? true : true);
  return (
    <SidecartContainer open={open} hide={hide}>

       // Thats the second button 
       // I want to close the sidebar component with this button
      <ExitButton hide={hide} onClick={() => setHide(!hide)}>
    </SidecartContainer>

const SidecartContainer = styled.div`
  transform: ${({ open, hide }) =>
    open && hide ? "translateX(0)" : "translateX(100%)"};
`;

我有一个按钮触发侧边栏的 Open state,当它打开时,我有一个 x 按钮来关闭侧边栏。

它只工作一次。

每当我单击打开按钮打开然后单击关闭隐藏时,我应该使用什么?

它是用样式组件制成的。

我认为您的问题是这一行const [hide, setHide] = useState(open? true: true); 仅在组件安装时运行一次。 您需要的是侧边栏中的useEffect来监听更改以open并将它们应用于hide state,如下所示:

const [hide, setHide] = useState(open ? true : true);

useEffect(() => {
  setHide(!open);
}, [open]);

  return (
    <SidecartContainer open={open} hide={hide}>

--------Thats the second button 
--------I want to close the sidebar component with this button
      <ExitButton hide={hide} onClick={() => setHide(!hide)}>


    </SidecartContainer>

我终于找到了正确的方法并且它有效。

首先,我在侧边栏之外声明了 useStates 逻辑:

  const [open, setOpen] = useState("");
  const hide = () => setOpen("translateX(100%)");
  const show = () => setOpen("translateX(0)");

然后我将道具传递给 Sidecart.js:

const SideCart = (props) => {
  return (
    <SidecartContainer transform={props.transform} open={props.open}>
      <ExitButton open={props.open} onClick={props.onClick}>
        <CloseIcon />
      </ExitButton>
      <ProductCards>
        <CartProductCard />
      </ProductCards>
      <Total></Total>
    </SidecartContainer>
  );
};

这也很重要,在样式组件 css 我声明了道具值:

const SidecartContainer = styled.div`
  transform: ${(props) => props.transform};
`;

最后我相应地更改了 onClick 功能:

  <SideCart transform={open} open={open} onClick={hide} />
  <CartButton open={open} onClick={show}>

暂无
暂无

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

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