我正在开发一个 Next.js 项目,其中有一个
StudentsPage.tsx
组件,其中包含一个用于导航到 NewStudent.tsx
页面的按钮。但是,NewStudent
组件不是导航到新页面,而是直接在 StudentsPage
上呈现。
如何修改此设置,以便单击“添加新”按钮导航到
NewStudent.tsx
页面?
这是我的代码:
StudentsPage.tsx:
import React from 'react';
import Link from 'next/link';
import NewStudent from './NewStudent';
const StudentsPage = () => {
return (
<div className="bg-white p-8 overflow-auto mt-16 h-screen">
<h1>Students Page</h1>
<Link href="/Admin/Students/NewStudent">
<button className="bg-blue-400 text-white p-2">
Add New
</button>
</Link>
<NewStudent />
</div>
);
};
export default StudentsPage;
**NewStudent.tsx:**
import React from 'react';
const NewStudent = () => {
return (
<div>NewStudent page</div>
);
};
export default NewStudent;
What I tried:
I tried using the Link component from Next.js to navigate from the StudentsPage to the NewStudent page. I also included the `<NewStudent />` component in `StudentsPage.tsx`, but it’s the same component that I want to open when the "Add New" button is clicked.
What I expected:
I expected that clicking the "Add New" button would take me to a new route `(/Admin/Students/NewStudent)` and display the `NewStudent.tsx` page separately.
What actually happened:
However, the `<NewStudent />` component is being rendered directly within the StudentsPage, instead of opening as a new page when the button is clicked. I'm looking for a way to make the button navigate to the new page, but it's not working as expected.
您需要阅读 docs 以了解路由在 NextJS 中的工作原理。
首先你的文件夹结构应该是:
/pages
└── /Admin
└── /Students
├── StudentsPage.tsx
└── NewStudent.tsx
其中
StudentsPage.tsx
是:
// pages/Admin/Students/StudentsPage.tsx
import React from 'react';
import Link from 'next/link';
const StudentsPage = () => {
return (
<div className="bg-white p-8 overflow-auto mt-16 h-screen">
<h1>Students Page</h1>
<Link href="/Admin/Students/NewStudent">
<button className="bg-blue-400 text-white p-2">
Add New
</button>
</Link>
{/* List of students would go here */}
</div>
);
};
export default StudentsPage;
和
NewStudent.tsx
:
// pages/Admin/Students/NewStudent.tsx
import React from 'react';
const NewStudent = () => {
return (
<div>
<h1>Add New Student</h1>
</div>
);
};
export default NewStudent;