如何使用 Next js 为组件定义路由?

问题描述 投票:0回答:1

在我的 Next.js 版本 14 应用程序中,我的应用程序/任务文件夹中有一个

page.tsx
文件。在该页面上,我有一个按钮可以打开对话框/弹出窗口来编辑任务:

如何在打开编辑对话框组件时将路径更改为

tasks/edit

这是迄今为止我的应用程序文件夹结构:

next.js navigation
1个回答
0
投票

要在 Next.js 版本 14 应用程序中打开编辑对话框组件时将路由更改为 /tasks/edit,可以使用 Next.js 提供的 useRouter 挂钩。

在 page.tsx 文件中,您可以执行以下操作:

import { useRouter } from 'next/router';

const YourPageComponent = () => {
const router = useRouter();

const handleEditButtonClick = () => {
// edit button cicked: Navigate to the edit route 
router.push('/tasks/edit');
};

return (
  <div>
    {/* Your content */}
    <button onClick={handleEditButtonClick}>Edit Task</button>
   {/*content other components */}
 </div>
);
};

export default YourPageComponent;

此代码片段假设您的 page.tsx 文件位于任务文件夹中,并负责渲染存在编辑按钮的页面。根据您的具体要求调整路径和逻辑。

© www.soinside.com 2019 - 2024. All rights reserved.