reactjs 路线项目的Next.js活动样式

xdnvmnnf  于 2022-12-22  发布在  React
关注(0)|答案(1)|浏览(110)

我一直在尝试在这个标题组件中的路线上使用主动样式(见下文)。对于如此简单的东西,我觉得我错过了一些明显的东西(对next/react来说仍然很新)。下面的代码有意义吗?

import Link from 'next/link';
import { useRouter } from 'next/router';
// import { NavLink } from '../../atoms/NavLink';
import styles from './Header.module.css'
import { meta } from "../../content/Content_option";

const path = [
  { uid: 21, name: ' Overview', id: 1, path: '/' },
  { uid: 31, name: 'Projects', id: 2, path: 'projects' },
  { uid: 41, name: 'What Im Reading', id: 3, path: 'readingList' },
  { uid: 51, name: 'Photos', id: 4, path: 'photos' },
  { uid: 61, name: 'Contact me', id: 5, path: 'contact' }
];
export default function Header() {
  const router = useRouter();
  const currentRoute = router.pathname;
  return (
    <header className={styles.nav}>      
      <div className={styles.navBackground}></div>
      <div className={styles.navContent}>
        <div className={styles.titleWrapper}>
          <div className={styles.navTitle}>{meta.title}</div>
          <div className={styles.navSubTitle}>{meta.roletitle}</div>
        </div>
        <div className={styles.navMenu}>
          <ul className={styles.navMenuItems}>
          {path.map((value) => {
              return (
                <li className={styles.navMenuItem} key={value.uid}>
                  <Link href={value.path} className={currentRoute === value.path ? styles.active : styles.nonActive}>
                    {value.name}
                  </Link>
                  {/* <NavLink activeClassName="active" href={value.path}>
                    {value.name}
                  </NavLink> */}
                </li>
              );
            })}
            </ul>
        </div>
      </div>
    </header>
  );
}

尝试添加条件currentRoute === value.path以触发活动类,但未获得任何结果。

<Link href={value.path} className={currentRoute === value.path ? styles.active : styles.nonActive}>
 {value.name}
</Link>
mfpqipee

mfpqipee1#

const path = [
  { uid: 21, name: ' Overview', id: 1, path: '/' },
  { uid: 31, name: 'Projects', id: 2, path: 'projects' },
  { uid: 41, name: 'What Im Reading', id: 3, path: 'readingList' },
  { uid: 51, name: 'Photos', id: 4, path: 'photos' },
  { uid: 61, name: 'Contact me', id: 5, path: 'contact' }
];

在路径中使用'/'...

const path = [
  { uid: 21, name: ' Overview', id: 1, path: '/' },
  { uid: 31, name: 'Projects', id: 2, path: '/projects' },
  { uid: 41, name: 'What Im Reading', id: 3, path: '/readingList' },
  { uid: 51, name: 'Photos', id: 4, path: '/photos' },
  { uid: 61, name: 'Contact me', id: 5, path: '/contact' }
];

相关问题