【问题标题】:How to make active Links in Next.JS using styled-components如何使用样式组件在 Next.JS 中创建活动链接
【发布时间】:2021-08-04 19:46:53
【问题描述】:

我在一个辅助项目中制作了一个简单的导航栏,并且在 Next.JS 中遇到了活动链接的问题,在反应中,您可以只使用 react-router-dom 具有具有 activeclass 属性的 Link 组件,但不能在 Next .JS(我认为)

【问题讨论】:

    标签: reactjs next.js styled-components


    【解决方案1】:

    您可以只使用useRouter 而不使用useState 来实现这一点(由于setState 是异步的,您宁愿使用不依赖于此的东西)。

      import { useRouter } from 'next/router';
      ...
      const router = useRouter();
    

    您的 Link 组件将如下所示:

    <Link href="/" passHref>
      <LinkText pathName={router.pathname}>Home</LinkText>
    </Link>
    

    最后,你的内部组件(在我的例子中,它是LinkText)会有这行:

    export const LinkText = styled.a`
      color: ${(props) => (props.href === props.pathName ? #728c69 : #fff)};
    `;
    

    【讨论】:

      【解决方案2】:

      为了让它工作,我使用了 UseRouter UseState 钩子

      const router = useRouter();
      const [pathName, setPathName] = useState(router.pathname);
      

      router.pathname 正在获取您网址上当前的 /[route]

      const newPathName = () => {
          setPathName(router.pathname);
        };
      
      <Link href="/" passHref>
             <StyledLink onClick={newPathName} pathname={pathName}>
               Home
             </StyledLink>
      </Link>
      

      通过将其用作 onClick 函数,它将 useState 设置为新路由

      StyledLink 是样式化的组件,点击后会改变颜色

      export const StyledLink = styled.a`
        color: ${(props) => (props.href === props.pathname ? "#a37600" : "#eaaa00")};
        text-decoration: none;
        padding-top: 20px;
        font-size: 1.3rem;
        :hover {
          text-decoration: underline;
          color: #a37600;
        }
      `;
      

      我基本上做了这个答案,因为我搜索了 30 分钟左右,但没有找到任何简单且实际上足够快的导航栏,如果有类似或更简单的答案,请将其链接给我。

      【讨论】:

      • 我发现我必须双击才能改变颜色。你也发现了这个吗?
      猜你喜欢
      • 2022-01-22
      • 2021-05-09
      • 1970-01-01
      • 2021-12-16
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-02-15
      • 1970-01-01
      相关资源
      最近更新 更多