On my layout component, I have two methods which toggle a menu open or force it closed. The toggle method works like a charm, however I want the menu to close when the user clicks on anything inside the header (so the menu doesn't stay open from page-to-page). However that part doesn't seem to want to work and I can't tell why.
Here is my code:
import React from 'react';
import Header from '../components/Header.jsx';
import Footer from '../components/Footer.jsx';
export default class Layout extends React.Component {
constructor(props) {
super(props);
this.state = {
mobileMenuVisible: false
}
}
handleNavClick() {
// Check if the menu is visible and then toggle to the other state
if(!this.state.mobileMenuVisible) {
this.setState({mobileMenuVisible: true});
} else {
this.setState({mobileMenuVisible: false});
}
}
forceCloseNav() {
// Don't perform checks, just set the menu visibility to false
this.setState({mobileMenuVisible: false});
}
render() {
const { dispatch } = this.props;
return(
<div class={'main menu-open-'+ this.state.mobileMenuVisible} role="main">
<span class="header-toggle" onClick={this.handleNavClick.bind(this)}><div><span>Menu</span></div></span>
<Header onClick={this.forceCloseNav.bind(this)}/>
<div class="wrapper">
{ this.props.children }
</div>
<Footer />
</div>
)
}
}
I've added console logs and I can see that the onClick handler on the component doesn't fire at all.
All looks correct in your example. But, can you check, how do you handle onClick
in your <Header />
component? It's a custom component, probably there are no clickHandlers there.
Below, you can see a working example with html <header>
(press run
)
class Test extends React.Component { constructor(props) { super(props); this.state = { mobileMenuVisible: false, }; } handleNavClick() { console.log('Nav open'); this.setState({mobileMenuVisible: true}); } forceCloseNav(event) { event.stopPropagation(); console.log('Nav close'); this.setState({mobileMenuVisible: false}); } render() { const { dispatch } = this.props; return( <div class={'main menu-open-'+ this.state.mobileMenuVisible} role="main"> <span class="header-toggle" onClick={this.handleNavClick.bind(this)}><div><span>Menu</span></div> </span> <header onClick={this.forceCloseNav.bind(this)}>Header content</header> <div class="wrapper"> { this.props.children } <hr /> { this.state.mobileMenuVisible ? 'Menu Visible' : 'Menu Hidden'} </div> <footer /> </div> ) } } ReactDOM.render(<Test />, document.body);
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.