当路由在Next.js中处于活动状态时,将目标活动链接定位

如何像在React-Router-4中那样将Next.js中的活动Link作为目标?意思是,当活动的路由处于活动状态时,给活动链接一个类吗?

2020/03/23 10:51:12

一个简单的基于useRouter钩子的解决方案

import Link from "next/link";
import { useRouter } from "next/router";


export const MyNav = () => {

  const router = useRouter();

  return (
    <ul>
      <li className={router.pathname == "/" ? "active" : ""}>
        <Link href="/">home</Link>
      </li>
      <li className={router.pathname == "/about" ? "active" : ""}>
        <Link href="/about">about</Link>
      </li>
    </ul>
  );
};

ProJinJin2020/03/23 10:51:12

另一个支持asprop的最低版本

import Link from "next/link";
import {withRouter} from "next/router";
import {Children} from "react";
import React from "react";

export default withRouter(({router, children, as, href, ...rest}) => (
   <Link {...rest} href={href} as={as}>
      {React.cloneElement(Children.only(children), {
         className: (router.asPath === href || router.asPath === as) ? `active` : null
      })}
   </Link>
));