gpt4 book ai didi

javascript - 如何让导航保持出现在桌面上? (ReactJS)

转载 作者:行者123 更新时间:2023-12-02 22:15:28 24 4
gpt4 key购买 nike

我创建了一个移动菜单,当我每次在桌面上显示导航时,它就会消失。我使用与为导航链接之一创建下拉菜单相同的 JS 效果。我不希望每次点击导航时导航都会消失。

如何让导航出现在桌面屏幕上?

View GIF Link

下面的代码:

import React from 'react';
import { Link } from 'react-router-dom';
import Dropdown from '../dropdowns/dropdown.js';
import hamburger from "../images/menu.svg";

class MobileDropdown extends React.Component {

constructor(){
super();

this.state = {
displayMenu: false,
};

this.showDropdownMenu = this.showDropdownMenu.bind(this);
this.hideDropdownMenu = this.hideDropdownMenu.bind(this);

};

showDropdownMenu(event) {
event.preventDefault();
this.setState({ displayMenu: true }, () => {
document.addEventListener('click', this.hideDropdownMenu);
});
}

hideDropdownMenu() {
this.setState({ displayMenu: false }, () => {
document.removeEventListener('click', this.hideDropdownMenu);
});

}


render() {
return (
<div className="FlexContainer NavbarContainer">

<div className="mobilecontainer LeftNav">
<h2 className="BrandName LeftNav mobileboxmenu inline">Kommonplaces</h2>
<div className="hamburger inline" onClick={this.showDropdownMenu}><img alt="menubtn" src={hamburger}></img></div>
</div>
{ this.state.displayMenu ? (

<>
<ul className="NavBar">
<Dropdown/>
<li className="RightNav"><Link to="/">Host Your Space</Link></li>
<li className="RightNav"><Link to="/">About Us</Link></li>
<li className="RightNav"><Link to="/">Contact Us</Link></li>
<li className="RightNav"><Link to="/">Sign Up</Link></li>
<li className="RightNav"><Link to="/">Login</Link></li>
</ul>
</>

):
(
null
)
}
</div>

);
}
}

export default MobileDropdown;

最佳答案

这是因为 showDropdownMenu 方法中有这一行:

document.addEventListener('click', this.hideDropdownMenu)

看起来您想要这样,以便您可以在移动断点中切换菜单的打开和关闭状态。

但问题是,当您转到桌面尺寸时,尽管您隐藏了按钮,但组件及其单击处理程序仍然在 DOM 中。因此,当您单击菜单项时,菜单项就会消失。

相对于你的问题和整个 React,我会考虑不要像在 vanilla JS 中那样添加事件监听器,而是使用 React 的 setState 来切换打开关闭,如下所示 this.state.displayMenu = !this.state .displayMenu 将切换状态对象的真/假值。

在更大的层面上,我会研究你如何组织你的组件。如果您有一个移动菜单组件,我会考虑拥有一个桌面菜单组件,并根据您是否处于移动断点有条件地渲染每个组件。

关于javascript - 如何让导航保持出现在桌面上? (ReactJS),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59395157/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com