简体   繁体   中英

How to make dropdown menu with styled-components?

How do I rewrite this dropdown menu with styled-components?

<!DOCTYPE html>
<html>
<head>
<style>
.dropdown {
  position: relative;
  display: inline-block;
}

.dropdown-content {
  display: none;
  position: absolute;
  background-color: #f9f9f9;
  min-width: 160px;
  box-shadow: 0px 8px 16px 0px rgba(0,0,0,0.2);
  padding: 12px 16px;
  z-index: 1;
}

.dropdown:hover .dropdown-content {
  display: block;
}
</style>
</head>
<body>

<h2>Hoverable Dropdown</h2>
<p>Move the mouse over the text below to open the dropdown content.</p>

<div class="dropdown">
  <span>Mouse over me</span>
  <div class="dropdown-content">
  <p>Hello World!</p>
  </div>
</div>

</body>
</html>

Source: https://www.w3schools.com/css/tryit.asp?filename=trycss_dropdown_text

So far, I've tried this:

  const NavbarDropdown = styled.div`
    position: relative;
    display: inline-block;

    &:hover {
      display: block;
    }
  `;
  const NavbarDropdownContent = styled.div`
    display: none;
    position: absolute;
    background-color: #f9f9f9;
    min-width: 160px;
    box-shadow: 0px 8px 16px 0px rgba(0, 0, 0, 0, 2);
    padding: 12px 16px;
    z-index: 1;
  `;

export const Navbar: React.FC = () => {
  return (
    <NavbarDropdown>
      <span>Menu</span>
      <NavbarDropdownContent>
        <Link to="/">Dropdown here</Link>
      </NavbarDropdownContent>
    </NavbarDropdown>
  );
};

It doesn't work and I don't know what to do next. Please help me.


PS I'm using React-v16.8.6, TypeScript-v3.4.5, Styled-components-v4.2.1

You should set NavbarDropdownContent 's display attr when hover.

  const NavbarDropdown = styled.div`
    position: relative;
    display: inline-block;

    &:hover {
      display: block;
      >div {
          display: block;
      }
    }
  `;

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