我在购物车中有一个按钮,我想在购物车打开时给它一个动画。为了定位它,我使用了 useRef 并尝试在控制台中登录结果:
const checkoutBtnRef = useRef("null");
useEffect(() => {
console.log(checkoutBtnRef.current);
}, [cartOpen]);
问题是当我打开购物车时 current 为空,只有在我关闭购物车时才返回实际按钮,我希望它是相反的。任何想法?
完整的组件代码
export default function TopNav() {
const classes = useStyles();
const [cartOpen, setCartOpen] = useState(false);
const checkoutBtnRef = useRef("null");
useEffect(() => {
console.log(checkoutBtnRef.current);
}, [cartOpen]);
return (
<>
<Container maxWidth="xl">
<div className={classes.root}>
<CardMedia
image="https://www.example.com"
className={classes.media}
/>
<SearchBar placeholder="Search" className={classes.searchBar} />
<div className={classes.iconsContainer}>
<PersonIcon className={classes.icon} />
<FavoriteBorderIcon className={classes.icon} />
<Badge
invisible={false}
variant="dot"
color="error"
onClick={() => setCartOpen(true)}
>
<ShoppingBasketIcon className={classes.icon} />
</Badge>
</div>
</div>
</Container>
<Drawer
classes={{
paper: classes.cart,
}}
anchor="right"
open={cartOpen}
transitionDuration={{ enter: 500, exit: 200 }}
onClose={() => setCartOpen(false)}
>
<div className={classes.topCartContent}>
<Typography variant="h5">Cart</Typography>
<CloseIcon
className={classes.closeIcon}
onClick={() => setCartOpen(false)}
/>
</div>
<Divider />
<List>
<CartItem />
</List>
<Button
classes={{
root: classes.checkoutBtn,
}}
variant="outlined"
onClick={() => setCartOpen(false)}
ref={checkoutBtnRef}
>
checkout
</Button>
</Drawer>
</>
);
}