在Next.js中的页面之间的链接

在Next.js中的页面之间的链接

在本文中,我们将看到如何在Next.js中将一个页面链接到另一个页面。按照以下步骤在Next.js应用程序中设置页面之间的链接:

在终端中运行以下命令来创建一个新的NextJs App:

npx create-next-app GFG

在创建项目文件夹后(即 GFG),请使用以下命令进入:

cd GFG

项目结构: 看起来会是这个样子。

在Next.js中的页面之间的链接

创建页面: 首先,我们将在我们的Next.js项目中创建两个不同的页面。为此,请在pages文件夹中创建两个名为’first’和’second’的新JavaScript文件。

文件名:first.js

Javascript

export default function first() {
    return (
        <div>
            This is the first page.
        </div>
    )
};

文件名:second.js

JavaScript

export default function second() {
    return (
        <div>
            This is the second page.
        </div>
    )
};

链接页面: 现在,要链接页面,我们将使用来自 ‘next/link’ 的 ‘Link’ 组件。我们可以在 Link 组件中添加 <a> 标签。我们可以在脚本中添加以下行以导入此组件。

import Link from 'next/link'

在我们的pages文件夹中的index.js文件中,我们将添加以下代码来将“第一页”和“第二页”链接到主页。

文件名:index.js

Javascript

// Importing the Link component
import Link from 'next/link'
 
export default function Home() {
    return (
        <div>
            {/* Adding Heading */}
            <h1>
                This is Homepage
            </h1>
 
            {/* Adding the Link Component */}
            <Link href="/first">
                <a><button>Go to First Page</button></a>
            </Link>
            <br />
            <Link href="/second">
                <a><button>Go to Second Page</button></a>
            </Link>
        </div>
    )
}

文件名:first.js 现在我们还要在我们的‘first’和‘second’页面中添加‘Link’组件。

JavaScript

// Importing the Link component
import Link from 'next/link'
 
export default function first() {
    return (
        <div>
            This is the first page.
            <br />
            {/* Adding the Link Component */}
            <Link href="/first">
                <a><button>Go to First Page</button></a>
            </Link>
            <br />
            <Link href="/second">
                <a><button>Go to Second Page</button></a>
            </Link>
        </div>
    )
}

文件名: second.js

JavaScript

// Importing the Link component
import Link from 'next/link'
 
export default function second() {
    return (
        <div>
            This is the second page.
            <br />
            {/* Adding the Link Component */}
            <Link href="/first">
                <a><button>Go to First Page</button></a>
            </Link>
            <br />
            <Link href="/second">
                <a><button>Go to Second Page</button></a>
            </Link>
        </div>
    )
}

运行应用程序的步骤: 现在使用以下命令运行应用程序:

npm start

输出:

在Next.js中的页面之间的链接

Python教程

Java教程

Web教程

数据库教程

图形图像教程

大数据教程

开发工具教程

计算机教程