简体   繁体   中英

onClick Event Using react-bootstrap nav dropdown and react-router-dom not working

I have the following Navbar using react-bootstrap. The second brand is always the one that is active, as if the dropdown is consistently clicked on the last item in the chain (in this case Tommy Hilfiger). I need to have the brand set based on which item in the dropdown is clicked.

const [brand, setBrand] = useState("");

 const brandSet = (value) => {
    setBrand(value);
  };

<Navbar bg="light" expand="lg">
          
              <NavDropdown title="Brands" id="basic-nav-dropdown">
                <NavDropdown.Item href="/#/products">
                  All Products
                </NavDropdown.Item>
                <NavDropdown.Item
                  href="/#/products:PoloRalphLauren"
                  onClick={brandSet("Polo Ralph Lauren")}
                >
                  Polo Ralph Lauren
                </NavDropdown.Item>
                <NavDropdown.Item
                  href="/#/products:TommyHilfiger"
                  onClick={brandSet("Tommy Hilfiger")}
                >
                  Tommy Hilfiger
                </NavDropdown.Item>

Because you are calling that function instead of passing the function to onClick, change that line to this:

        <NavDropdown.Item
             href="/#/products:PoloRalphLauren"
             onClick={() => brandSet("Polo Ralph Lauren")}
         >
            Polo Ralph Lauren
        </NavDropdown.Item>

=> called Arrow Function, which was introduced in ES6, and will be supported on React 0.13.3 or upper.

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