【问题标题】:Target specific class using Styled Components React.js使用样式化组件 React.js 定位特定类
【发布时间】:2020-11-24 02:54:20
【问题描述】:

我正在尝试向导航栏组件添加主题。该组件具有向下滚动时显示粘性导航栏的功能。向下滚动窗口后,我真的被困在“粘性”类上。这适用于普通的 css,但是一旦我将它添加到 styled-component 并将其从 css 中删除,它就不起作用了。

也许我没有正确定位 className 'sticky'?

有什么建议吗??谢谢!

    export function Nav() {
      const [theme, setTheme] = useState("light");
      const [theTheme, setTheTheme] = useGlobal("onTheme");

      useEffect(() => {
        if (theTheme == false) setTheme("dark");
        else setTheme("light");

   
        window.addEventListener("scroll", function () {
        var header = document.querySelector("header");
        header.classList.toggle("sticky", window.scrollY > 0);
    });
  });

  return (
    <ThemeProvider theme={getTheme(theme)}>
      <Head>
        <Navbar>
          <NavLink></NavLink>
          <NavItem icon={<CaretIcon />}>
            <DropdownMenu />
          </NavItem>
        </Navbar>
      </Head>
    </ThemeProvider>
  );
}

我可以使用普通 CSS 定位“粘性”类。

    header.sticky {
      background-color: rgb(31, 31, 37);
    }

我正在尝试使用样式化组件来定位“粘性”。

    export const Head = styled.header`
      position: fixed;
      width: 100%;
      background-color: transparent;
      top: 0rem;
      transition: 0.6s;
      z-index: 100000;
      text-decoration: none;
      & .sticky {
        background-color: ${(props) => props.theme.hoverColor};
       } 
     `;

【问题讨论】:

    标签: javascript css reactjs jsx styled-components


    【解决方案1】:

    看起来&amp; .sticky 之间的一个不必要的空格最终会申请孩子而不是标题本身。正确的应该是:

    export const Head = styled.header`
      position: fixed;
      width: 100%;
      background-color: transparent;
      top: 0rem;
      transition: 0.6s;
      z-index: 100000;
      text-decoration: none;
    
      &.sticky {
         background-color: ${(props) => props.theme.hoverColor};
      } 
    `;
    

    【讨论】:

    • 哇,我觉得自己太笨了!非常感谢,它现在可以完美运行了。
    猜你喜欢
    • 2017-12-31
    • 2023-03-27
    • 2020-01-19
    • 2014-05-05
    • 2021-12-12
    • 2021-11-02
    • 2022-06-23
    • 2020-11-30
    • 2023-03-22
    相关资源
    最近更新 更多