react-bootstrap how to collapse menu when item is selected

纵饮孤独 提交于 2019-12-01 19:02:06

问题


How do you make the menu collapse after item is selected?

I dont know how to make it work on fiddle, but this is what I would do? https://jsfiddle.net/vjeux/kb3gN/

import React from 'react';
import {Navbar, Nav, NavItem, NavDropdown, DropdownButton, MenuItem, CollapsibleNav} from 'react-bootstrap';

export default class App extends React.Component {

    constructor(props) {
      super(props);
      this.onSelect = this.onSelect.bind(this);
      this.toggleNav = this.toggleNav.bind(this);
      // this.state = {navExpanded: false};
    }

    onSelect(e){
        console.log('OnSelect')
        // console.log(this.state.navExpanded);
        // this.setState({navExpanded: false});
    }

    toggleNav(){console.log('toggle...')};

    // <Navbar inverse fixedTop toggleNavKey={0} navExpanded={this.state.navExpanded} onToggle={() => this.toggleNav()}>
    // <Navbar inverse fixedTop toggleNavKey={0} navExpanded={this.state.navExpanded} >

    render() {
        return (

          <Navbar inverse fixedTop toggleNavKey={0} >
            <Nav right eventKey={0} onSelect={this.onSelect} > {/* This is the eventKey referenced */}
              <NavItem eventKey={1} href="#">Link</NavItem>
              <NavItem eventKey={2} href="#">Link</NavItem>
            </Nav>
          </Navbar>     

      )

    }

    componentDidMount() {

    }
}

React.render(<App />, document.getElementById('example'));

回答1:


i have found the solution from this link https://github.com/react-bootstrap/react-bootstrap/issues/1301

i will put sample code of the link above here

const Menu = React.createClass ({
  getInitialState () {
    return {
      navExpanded: false
    }
  },

  setNavExpanded(expanded) {
    this.setState({ navExpanded: expanded });
  },

  closeNav() {
    this.setState({ navExpanded: false });
  },

  render() {
    return (
      <div>
        <Navbar onToggle={this.setNavExpanded}
                expanded={this.state.navExpanded}>
          <Navbar.Header>
            <Navbar.Brand>
              <Link to="some url">Main</Link>
            </Navbar.Brand>
            <Navbar.Toggle />
          </Navbar.Header>
          <Navbar.Collapse>
            <Nav onSelect={this.closeNav}>
              { this.renderMenuItem() }
            </Nav>
          </Navbar.Collapse>
        </Navbar>
      </div>
    )
  }



回答2:


<Navbar collapseOnSelect ... > should do the job, but it works unstable :(




回答3:


Slightly related to issue, might be helpful for someone This is what I did for closing navbar when clicked outside the menu

class Menu extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      isNavExpanded: false
    };
  
    this.setIsNavExpanded = (isNavExpanded) => {
      this.setState({ isNavExpanded: isNavExpanded });
    }
  
    this.handleClick = (e) => {
      if (this.node.contains(e.target)) {
        // if clicked inside menu do something
      } else {
        // If clicked outside menu, close the navbar.
        this.setState({ isNavExpanded: false });
      }
    }
  }
  componentDidMount() {
    document.addEventListener('click', this.handleClick, false);      
  }

  componentWillUnmount() {
    document.removeEventListener('click', this.handleClick, false);
  }

  render() {
    return (
      <div ref={node => this.node = node}
        <Navbar collapseOnSelect
           onToggle={this.setIsNavExpanded}
           expanded={this.state.isNavExpanded}
           >
          <Navbar.Collapse>
            // Nav Items
          </Navbar.Collapse>
        </Navbar>
      </div>
    )
  }



回答4:


Well for anyone wondering, and coming here in 2019, maybe you are using react-router, and as result, instead of the Nav.Link that are the default component for the Navbar you use Link from react-router.

And what did you find ? That in result the mobile menu is not working as expected and not closing after clicking on a link, and nothing seems to work.

Here is my "simple" solution (Using hooks) to that problem:

First we set up a hook:

const [expanded, setExpanded] = useState(false);

Second in the Navbar we add this prop:

<Navbar expanded={expanded}>

Now we have control over the visibilty of the menu, in the "first" load it will show hidden.

Third we add an onClick event to the toggle handler that changes the menu between visibility status:

<Navbar.Toggle onClick={() => setExpanded(expanded ? false : "expanded")} />

Fourth we add the prop onClick={() => setExpanded(false)} to all our Link components from react-router inside our Navbar.

Profit! I swear that after more than 1 hour wondering for the internet is the easiest and cleanest solution I found.




回答5:


For me works the decision of Josef I implemented all four points. But I have some other makeup:

            <Navbar expanded={expanded} bg="light" expand="lg" className="p-3">
            <Navbar.Brand href="/"><img src={CarLogo} alt="Tim-Tim auto" title="Tim-Tim auto" /></Navbar.Brand>
            <Navbar.Toggle onClick={() => setExpanded(expanded ? false : "expanded")} aria-controls="basic-navbar-nav" />
                <Navbar.Collapse id="basic-navbar-nav" className="justify-content-end">
                    <Nav> 
                        <Nav.Item><NavLink onClick={() => setExpanded(false)} exact to='/'>Home</NavLink></Nav.Item>
                        <Nav.Item><NavLink onClick={() => setExpanded(false)} to='/Cars'>Cars</NavLink></Nav.Item>
                        <Nav.Item><NavLink onClick={() => setExpanded(false)} to='/about'>About</NavLink></Nav.Item>
                        <Nav.Item><NavLink onClick={() => setExpanded(false)} to='/news'>News</NavLink></Nav.Item>
                        <Nav.Item><NavLink onClick={() => setExpanded(false)} to='/contacts'>Contacts</NavLink></Nav.Item>
                    </Nav>
                </Navbar.Collapse>
            </Navbar>


来源:https://stackoverflow.com/questions/32452695/react-bootstrap-how-to-collapse-menu-when-item-is-selected

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!