我正在开发基于react类的组件我有汉堡包[https://easyupload.io/isutmy]每当我点击关闭汉堡时,它就可以正常工作,但我需要的是每当我点击网页外时,它就会关闭。
请参考代码-
import '../scss/header.scss';
import { Link } from 'react-router-dom';
import { NavLink } from 'react-router-dom';
import {routes} from '../routes';
class Header extends Component {
constructor(props) {
super(props);
this.state = {
url: window.location.href,
isOtherPage: true
}
this.setState = this.state.url;
}
getUrls = (e) => {
console.log(e.target.pathname);
const isHomePage = e.target.pathname === '/';
this.menuToggle()
var element = document.getElementById("header");
if (isHomePage) {
element.classList.remove("header2");
element.classList.add("header1");
} else {
element.classList.remove("header1");
element.classList.add("header2");
}
this.setState = { isOtherPage: isHomePage };
}
menuToggle = (e) => {
var menuClass = document.getElementById("menu");
menuClass.classList.toggle('menuOpen');
// console.log(e)
}
jsx从这里开始,请检查并提供我犯错误的的解决方案
return (
<div>
<header>
<div id="header" className={'header header1'}>
{/* {headerBg} */}
<div className="topbar">
<div className="logo">
<a href="#" className="animated bounceInDown"><img src='/media/logo.png' alt="Logo" /></a>
</div>
<div className="menu-cover top-nav">
<div className="menus">
<div className="menu-res">
{/* <h2><i class="fa fa-bars"></i></h2> */}
<input id="menu-toggle" type="checkbox" />
<label class='menu-button-container' for="menu-toggle">
<div onClick={this.menuToggle} class='menu-button'></div>
</label>
</div>
<ul id="menu" className=" menu animated">
<li><NavLink exact onClick={this.getUrls.bind(this)} to="/" activeClassName="active">Home</NavLink></li>
<li><NavLink onClick={this.getUrls.bind(this)} to="/about" activeClassName="active" className="">About</NavLink></li>
<li><NavLink onClick={this.getUrls.bind(this)} to="/careers" activeClassName="active">Career</NavLink></li>
<li><NavLink onClick={this.getUrls.bind(this)} to="/contact" activeClassName="active">Contact</NavLink></li>
<a className="login-b" href="">Login</a>
</ul>
</div>
</div>
</div>
<div className="clearfix"></div>
</div> </header>
{this.props.children}
</div>
)
}
}
export default Header;```
[1]: https://i.stack.imgur.com/ZBNZG.png
我不能保证这会起作用,但您可能想尝试在<ul>
标签上设置onBlur
<ul id="menu" className=" menu animated" onBlur={() => callSomeFunctionToSetClassname()}>