Javascript 在Next.js中为导航链接添加活动类
我正在使用并希望在导航链接的页面与url匹配时向导航链接添加活动类。但我也希望它在url比页面更深时处于活动状态 例如,指向Javascript 在Next.js中为导航链接添加活动类,javascript,reactjs,frontend,next.js,Javascript,Reactjs,Frontend,Next.js,我正在使用并希望在导航链接的页面与url匹配时向导航链接添加活动类。但我也希望它在url比页面更深时处于活动状态 例如,指向/register的导航链接将在以下情况下处于“活动”状态: /register /注册/注册 这是我为Next.js编写的NavLink组件。它与链接具有相同的API,并添加了两个道具: 当链接匹配时将应用于链接的activeClassName (可选)精确-防止匹配“更深”路线) 从“React”导入React; 从“下一个/链接”导入链接; 从“下一个/路由器”
/register
的导航链接将在以下情况下处于“活动”状态:
/register
/注册/注册
- 这是我为Next.js编写的
NavLink
组件。它与链接
具有相同的API,并添加了两个道具:
- 当链接匹配时将应用于链接的
activeClassName
- (可选)
-防止匹配“更深”路线)精确
从“React”导入React;
从“下一个/链接”导入链接;
从“下一个/路由器”导入{useRouter};
导出默认函数NavLink({href,as,exact,activeClassName,children,…props}){
const{asPath}=useRouter();
//将路径规格化并拆分为其段
常量段=(p)=>新URL(p,'http://example.com“).pathname.split(“/”).filter(s=>s);
const currentPath=段(asPath);
const targetPath=段(如| | href);
//如果以下所有条件均为真,则路由处于活动状态:
//1.当前路由中的段数至少与目标路由中的段数相同
//2.当前路由与目标路由匹配
//3.如果处于“精确”模式,则末端没有额外的路径段
常数isActive=currentPath.length>=targetPath.length
&&targetPath.every((p,i)=>currentPath[i]==p)
&&(!exact | | targetPath.length==currentPath.length);
const child=React.Children.only(Children);
const className=((child.props.className | |“”)+“”+(isActive?activeClassName:“”)).trim();
返回(
{React.cloneElement(子,{className}}
);
}
通过依赖模块中的路由匹配功能,可以使这一过程更简单、更健壮,该功能已经是Next.js的依赖项:
import React from 'react';
import Link from 'next/link';
import { useRouter } from 'next/router';
import { pathToRegexp } from 'path-to-regexp';
export default function NavLink({ href, as, exact, activeClassName, children, ...props }) {
const { asPath } = useRouter();
const isActive = pathToRegexp(as || href, [], { sensitive: true, end: !!exact }).test(asPath);
const child = React.Children.only(children);
const className = ((child.props.className || '') + ' ' + (isActive ? activeClassName : '')).trim();
return (
<Link href={href} as={as} {...props}>
{React.cloneElement(child, { className })}
</Link>
);
}
从“React”导入React;
从“下一个/链接”导入链接;
从“下一个/路由器”导入{useRouter};
从'path to regexp'导入{pathToRegexp};
导出默认函数NavLink({href,as,exact,activeClassName,children,…props}){
const{asPath}=useRouter();
const isActive=pathToRegexp(as | | href,[],{sensitive:true,end:!!exact});
const child=React.Children.only(Children);
const className=((child.props.className | |“”)+“”+(isActive?activeClassName:“”)).trim();
返回(
{React.cloneElement(子,{className}}
);
}
next.js是什么?显然是一个JavaScript文件,但它可以包含任何内容,根据您的帖子中提供的小信息,有人应该如何帮助?@SPlatte..我认为这是显而易见的,因为它在业界非常有名。对任何不熟悉react的人来说都不是。您尝试过将URI嵌入iframe吗?没有。我认为这太过分了。我用过这个,它工作得很好(),但只适用于一层。它不适用于更深层的分段URL@splaten