【问题标题】:Trigger Sidebar from two different button using State in React && styled-components使用 React && styled-components 中的 State 从两个不同的按钮触发侧边栏
【发布时间】:2022-01-16 13:58:42
【问题描述】:

第一个按钮:

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%)"};
`;

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

它只工作一次。

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

它是用样式组件制作的。

【问题讨论】:

    标签: reactjs use-effect use-state


    【解决方案1】:

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

    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>
    

    【讨论】:

    • 不,这并没有真正起作用..谢谢
    【解决方案2】:

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

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

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

    然后我将 props 传递给 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 中我声明了 prop 值:

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

    最后我相应地更改了 onClick 函数:

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

    【讨论】:

      猜你喜欢
      • 2021-06-05
      • 2021-07-17
      • 1970-01-01
      • 2021-01-09
      • 2019-02-18
      • 1970-01-01
      • 2021-07-15
      • 2020-06-28
      • 2020-10-19
      相关资源
      最近更新 更多