我在Gatsby应用程序中使用react burger菜单创建了一个工作的burger菜单。我正试图获得它,这样当点击汉堡中的AnchorLink时,汉堡菜单就会关闭。我试过按照文档中的建议进行<Menu isOpen={ false }>
,但没有成功。有什么帮助吗?
这是我的汉堡菜单代码:
import React from "react"
import { slide as Menu } from "react-burger-menu"
import { AnchorLink } from "gatsby-plugin-anchor-links"
const Burger = () => {
return (
<div className="burger-menu">
<Menu right isOpen={ false }>
<AnchorLink to="/#about">About Me</AnchorLink>
<AnchorLink to="/#experience">Experience</AnchorLink>
<AnchorLink to="/#projects">Projects</AnchorLink>
<AnchorLink to="/#contact">Contact</AnchorLink>
</Menu>
</div>
)
}
export default Burger
您可以为Menu
和AnchorLink
提供事件处理程序,并添加状态menuOpen
来关闭/打开侧边栏。
const Burger = () => {
const [menuOpen, setMenuOpen] = React.useState(false)
// This keeps your state in sync with the opening/closing of the menu
// via the default means, e.g. clicking the X, pressing the ESC key etc.
const handleStateChange = state => {
setMenuOpen(state.isOpen)
}
// This can be used to close the menu, e.g. when a user clicks a menu item
const closeMenu = () => {
setMenuOpen(false)
}
return (
<div className="burger-menu">
<Menu
right
isOpen={menuOpen}
onStateChange={state => handleStateChange(state)}
>
<AnchorLink
to="/#about"
onClick={() => {
closeMenu()
}}
>
About Me
</AnchorLink>
<AnchorLink
to="/#experience"
onClick={() => {
closeMenu()
}}
>
Experience
</AnchorLink>
<AnchorLink
to="/#projects"
onClick={() => {
closeMenu()
}}
>
Projects
</AnchorLink>
<AnchorLink
to="/#contact"
onClick={() => {
closeMenu()
}}
>
Contact
</AnchorLink>
</Menu>
</div>
)
}