Next.js使用component附加到slug/url< Link>

u59ebvdq  于 2023-06-22  发布在  其他
关注(0)|答案(1)|浏览(122)

我在Next.js项目中有以下基于文件夹的结构。

/dashboard/[appid]/users/[userid]/user_info.tsx

我在用户页面上使用了Next.js的内置组件href={"user_info"}。我希望URL动态地指向/dashboard/app_01/users/123123123/user_info。但是,我目前被重定向到根级别/user_info,该级别不存在。
next.js react组件看起来像这样:

'use client';

import Link from 'next/link';
import React from 'react';
import Image from 'next/image';

type sidebarbuttonprops = {
    text: string,
    to?: string,
    id: string,
    active?: string,
    disabled?: string[],
    icon?: string,
    getButtonValue: (buttonid: string) => void
}

export const SideBarButton = ({ text, to: link, id, active, disabled, icon, getButtonValue }: sidebarbuttonprops) => {
    let buttonActive: boolean = id == active ? true : false;
    let buttonDisabled: boolean | undefined = disabled?.includes(id);
    const handleClick = (e: React.MouseEvent<HTMLElement>) => {
        if (!buttonDisabled) {
            getButtonValue(id);
        }
    }

    return <Link className="sidebar-button" role='link' href={!buttonDisabled ? link! : ''} replace={false} onClick={handleClick}>
        <div className={`sidebar-button__container${buttonActive ? ' button_active' : ''}${buttonDisabled ? ' button_disabled' : ''}`} id={id}>
            <div className='sidebar-button__svg'>
                {icon != undefined && <Image src={icon!} alt="icon" width={25} height={25} />}
            </div>
            <div className='sidebar-button__text'>
                <span className='sidebar-button__span'>
                    {text}
                </span>
            </div>
        </div>
    </Link>;
}

生成的链接HTML如下所示:

<a class="sidebar-button" role="link" href="user_info">"[Some divs]"</a>

值得注意的是,当鼠标悬停在链接上时,屏幕底部的URL滑块会显示正确的URL /dashboard/app_01/users/123123123/user_info。尽管如此,点击链接会将我重定向到网站的一个不正确的部分。如果我点击DevTools中的链接,我将被引导到正确的位置。
TL;DR:如何动态地将user_info附加到当前URL,而不需要写下整个URL?

vohkndzv

vohkndzv1#

在eten在next.js < 13中强调了一种方法之后,我自己找到了答案。
在Next.js > 13中,您需要使用usePathname来获取当前路径,然后可以向其追加

import { usePathname } from 'next/navigation';

 export default function Page() {
     const current_path = usePathname(); // current path
     ...

相关问题