gpt4 book ai didi

javascript - 在 Next.js 中为导航链接添加事件类

转载 作者:行者123 更新时间:2023-12-03 23:08:49 24 4
gpt4 key购买 nike

我正在使用 Next.js并希望在链接到的页面与 url 匹配时将事件类添加到导航链接。但我也希望它在 url 比页面更深时处于事件状态。
例如,指向 /register 的导航链接将是“活跃的”:

  • /register
  • /register/sign-up
  • 最佳答案

    这是 NavLink我为 Next.js 编写的组件。它具有与 Link 相同的 API ,加上两个 Prop :

  • 一个 activeClassName当它匹配
  • 时将应用于链接
  • (可选)exact - 防止匹配“更深”的路线)

  • import React from 'react';
    import Link from 'next/link';
    import { useRouter } from 'next/router';

    export default function NavLink({ href, as, exact, activeClassName, children, ...props }) {
    const { asPath } = useRouter();
    // Normalize and split paths into their segments
    const segment = (p) => new URL(p, 'http://example.com').pathname.split('/').filter(s => s);
    const currentPath = segment(asPath);
    const targetPath = segment(as || href);
    // The route is active if all of the following are true:
    // 1. There are at least as many segments in the current route as in the destination route
    // 2. The current route matches the destination route
    // 3. If we're in “exact" mode, there are no extra path segments at the end
    const 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();

    return (
    <Link href={href} as={as} {...props}>
    {React.cloneElement(child, { className })}
    </Link>
    );
    }
    通过依赖 path-to-regexp 中的路由匹配功能,可以使这更简单、更健壮。模块,它已经是 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>
    );
    }

    关于javascript - 在 Next.js 中为导航链接添加事件类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60324081/

    24 4 0
    Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
    广告合作:1813099741@qq.com 6ren.com