[英]Trigger Sidebar from two different button using State in React && styled-components
The first button:第一个按钮:
const [open, setOpen] = useState(false);
return (
<>
<SideCart open={open} />
<CartButton open={open} onClick={() => setOpen(!open)}>
)
</>
The sidebar:侧边栏:
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%)"};
`;
I have one button triggering the Open state of sidebar and when it opens I have an x button to close the sidebar.我有一个按钮触发侧边栏的 Open state,当它打开时,我有一个 x 按钮来关闭侧边栏。
It only works once.它只工作一次。
What shall I use so whenever I click the open button to open and then when I click on close to hide?每当我单击打开按钮打开然后单击关闭隐藏时,我应该使用什么?
It's made with styled-components.它是用样式组件制成的。
I think your problem is that this line const [hide, setHide] = useState(open? true: true);
我认为您的问题是这一行
const [hide, setHide] = useState(open? true: true);
only runs once on component mount.仅在组件安装时运行一次。 What you need is a
useEffect
in the sidebar to listen for changes to open
and apply them to the hide
state like so:您需要的是侧边栏中的
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>
I finally found what's the right way to do it and it works.我终于找到了正确的方法并且它有效。
First I declared outside of the sidebar the useStates logic:首先,我在侧边栏之外声明了 useStates 逻辑:
const [open, setOpen] = useState("");
const hide = () => setOpen("translateX(100%)");
const show = () => setOpen("translateX(0)");
then I passed the props to Sidecart.js:然后我将道具传递给 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>
);
};
also this is important, in the styled component css I declared the prop value:这也很重要,在样式组件 css 我声明了道具值:
const SidecartContainer = styled.div`
transform: ${(props) => props.transform};
`;
Finally I changed the onClick functions accordingly:最后我相应地更改了 onClick 功能:
<SideCart transform={open} open={open} onClick={hide} />
<CartButton open={open} onClick={show}>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.