简体   繁体   中英

Loading react-bootstrap's Dropdown data on mouse hover than on mouse click in React functional component?

I need to make the dropdown open and load the dropdown items when mouse hover rather than on click.

Currently my code is as follows:

function Navigation(){

  const [isOpen, setIsOpen] = useState(false);
  return (
    <Nav className="ml-auto">
        <NavDropdown
          title="About"
          onMouseEnter={() => setIsOpen(true)}
          onMouseLeave={() => setIsOpen(false)}
          show={isOpen}
        >
          <NavDropdown.Item href="#action/1.1">Who we are</NavDropdown.Item>
          <NavDropdown.Item href="#action/2.2">
            How we work
          </NavDropdown.Item>
          <NavDropdown.Item href="#action/2.2">
            Certifications
          </NavDropdown.Item>
        </NavDropdown>

        <NavDropdown
          title="Services"
          onMouseEnter={() => setIsOpen(true)}
          onMouseLeave={() => setIsOpen(false)}
          show={isOpen}
        >
          <NavDropdown.Item href="#action/2.1">
            Cloud Digital Transformation
          </NavDropdown.Item>
          <NavDropdown.Item href="#action/2.2">
            Expert Cloud Advise and Support
          </NavDropdown.Item>
          <NavDropdown.Item href="#action/2.3">
            Software Development
          </NavDropdown.Item>
          <NavDropdown.Item href="#action/2.4">
            Dedicated Teams
          </NavDropdown.Item>
        </NavDropdown>

        <NavDropdown
          title="Contact"
          onMouseEnter={() => setIsOpen(true)}
          onMouseLeave={() => setIsOpen(false)}
          show={isOpen}
        >
          <NavDropdown.Item href="#sales">Sales</NavDropdown.Item>
          <NavDropdown.Item href="#support">Support</NavDropdown.Item>
        </NavDropdown>
      </Nav>
  )
}

However, when I hover over the items in the navbar, all the items from all three navdropdown is shown at the same time when I hover the mouse over any of them. Can anyone assist me with the solution? What attribute should I pass in to achieve that?

You should refactor your functional component like this:

function Navigation() {

  const [shouldOpen, show] = useState(false);

  return (
    <NavDropdown 
       title="About"
       onMouseEnter = { () => show(true) }
       onMouseLeave = { () => show(false) }
       show={ this.shouldOpen }>
      <NavDropdown.Item href="#action/1.1">Who we are</NavDropdown.Item>
      <NavDropdown.Item href="#action/2.2">
        How we work
      </NavDropdown.Item>
      <NavDropdown.Item href="#action/2.2">
        Certifications
      </NavDropdown.Item>
    </NavDropdown>
  )
}

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