使用样式化组件React.js以特定类为目标 [英] Target specific class using Styled Components React.js

查看:38
本文介绍了使用样式化组件React.js以特定类为目标的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试向导航栏组件添加主题。该组件具有向下滚动时显示粘滞导航栏的功能。一旦窗口向下滚动,我就会把目标锁定在"粘性"类上。这对普通CSS有效,但是一旦我将其添加到样式组件并从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将"Sticky"类作为目标。

    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};
       } 
     `;

推荐答案

看起来& .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};
  } 
`;

这篇关于使用样式化组件React.js以特定类为目标的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆