首页 > 解决方案 > Styled-Components 条件样式渲染的问题。我不确定出了什么问题

问题描述

我正在尝试打开和关闭汉堡菜单。我已经登录控制台检查布尔值是否正在改变,但 css 没有。

我的问题是“props.active?” 它正在工作,但“.mobile-menu”类没有改变。我不完全确定我需要做什么才能让它工作。我试图更改我想要影响的样式,因为我认为您可能无法切换为显示,但是,可见性和不透明度仍然没有改变。

import { useState } from "react";
import styled from "styled-components";

import logo from "./assets/logo.svg";

const StyledHeader = styled.header`
  ---

  button {
    ---
    span {
     ---
      &:nth-child(even) {
        margin: 5px 0;
      }
    }
  }
  .mobile-menu {
    position: absolute;
    right: 100px;
    top: 100px;
    display: ${(props) => (props.active ? "none" : "block")};
    height: 330px;
    width: 330px;
    background: #e210e2;
    color: white;
    ul {
     ----
    }
  }
`;

const Header = () => {
  const [active, setActive] = useState(false);

  return (
    <StyledHeader>
      <img src={logo} alt="sunnyside logo" />
      <button onClick={() => setActive(!active)}>
        {console.log(active)}
        <span></span>
        <span></span>
        <span></span>
      </button>
      <nav className="mobile-menu" active>
        <ul>
          <li>About</li>
          <li>Services</li>
          <li>Projects</li>
          <li>Contact</li>
        </ul>
      </nav>
    </StyledHeader>
  );
};

export default Header;

标签: reactjsstyled-components

解决方案


请在 StyledHeader 标签中传递道具。

按照下面的代码:

<StyledHeader active={active}>
....
</StyledHeader>

推荐阅读