简体   繁体   中英

Hamburger menu toggle state is not toggling in ReactJS

I'm trying to fix a bug on mobile view for a hamburger menu in ReactJS. Currently, the menu opens when clicked but it stays open when a user switches between different pages (components).

I setup an onClick event for the menu items to run a function that should change the state of the component to hide the navbar but its not changing the state.

Here's my component:

class Navigation extends React.Component{
  constructor(props){
    super(props);
    this.token = this.props.token;
    this.state = {
      isToggle: true,
    };

    let memberFunctions = Object.getOwnPropertyNames(Navigation.prototype);
    for (let functionName of memberFunctions) {
      if (functionName.startsWith('handle')) {
        this[functionName] = this[functionName].bind(this);
      }
    }
  }
handleResetHamburger() {
    console.log('reset burgers');
    console.log('before state', this.state);
    this.setState({
      isToggle : true,
    });
    console.log('after state', this.state);
  }

Here's a selection (I edited out parts that aren't relevant. if thats not helpful I can add them back in) from render part of the component:

render(){    


    return (
      <section className="navigation schoger-border is-transparent">
        <nav className="navbar is-white">



          <div className="navbar-menu" id='navbar-menu-id'>
            <div className="navbar-start"></div>

            <div className="navbar-end" id="Options">
              <Link to="/" className="navbar-item has-text-centered" onClick= {this.handleResetHamburger}>Home</Link>
              {handleLoginVsLogout}
              <Link to="/about" className="navbar-item has-text-centered" onClick={this.handleResetHamburger}>About Us</Link>
            </div>
          </div>

          <div className="navbar-item"></div>

        </nav>
      </section>);
  }
}

I've tried a variety of different syntax including what the reactJS docs have listed for handling events .

Here's a link to the full file on github.

Thanks for your help! Long time lurker, second time questioner here.

here is a simple toggle method:

toggleMenu(){
    this.setState({isToggle: !this.state.isToggle});
}

also i would add a variable in the render method to hold a className for the toggle state:

render(){
    let menuClassName = this.state.isToggle ? "toggle-open" : "toggle-closed";
    ...
    <div className=`nav-menu ${menuClass}`>
    ...
    </div>
}

if you only want to hide the menu on a link click just set the isToggle state to false.

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM