当前位置 博文首页 > 使用路由器检测Next.js中的活动链接_cuk0051的博客:next.js 多

    使用路由器检测Next.js中的活动链接_cuk0051的博客:next.js 多

    作者:[db:作者] 时间:2021-08-29 10:18

    next.js 多级路由

    One very important feature when working with links is determining what is the current URL, and in particular assigning a class to the active link, so we can style it differently from the other ones.

    使用链接时,一个非常重要的功能是确定当前URL是什么,尤其是为活动链接分配一个类,因此我们可以将其样式设置为与其他URL不同。

    This is especially useful in your site header, for example.

    例如,这在您的网站标题中特别有用。

    The Next.js default Link component offered in next/link does not do this automatically for us.

    next/link中提供的Next.js默认Link组件不会自动为我们执行此操作。

    We can create a Link component ourselves, and we store it in a file Link.js in the Components folder, and import that instead of the default next/link.

    我们可以自己创建一个Link组件,然后将其存储在Components文件夹中的Link.js文件中,然后导入它而不是默认的next/link

    In this component, we’ll first import React from react, Link from next/link and the useRouter hook from next/router.

    在此组件中,我们将首先从react导入React,从next/link导入Link,从next/router useRouter钩子。

    Inside the component we determine if the current path name matches the href prop of the component, and if so we append the selected class to the children.

    在组件内部,我们确定当前路径名是否与组件的href属性匹配,如果是,则将selected类附加到子代。

    We finally return this children with the updated class, using React.cloneElement():

    最后,我们使用React.cloneElement()返回带有更新类的子级:

    import React from 'react'
    import Link from 'next/link'
    import { useRouter } from 'next/router'
    
    export default ({ href, children }) => {
      const router = useRouter()
    
      let className = children.props.className || ''
      if (router.pathname === href) {
        className = `${className} selected`
      }
    
      return <Link href={href}>{React.cloneElement(children, { className })}</Link>
    }
    cs