本篇介绍Next的文件夹结构以及Next.js的路由系统

Next.js 文件夹基本结构

image-20231030194032061

对应的Tree命令结构如下:

.
├── favicon.ico				
├── globals.css	      # 全局样式
├── layout.tsx        # 全局layout
├── module-1          # 模块-1
│   ├── layout.tsx    # 模块-1的layout
│   └── page.tsx      # 模块-1的页面入口文件,访问方式 http://localhost:8080/module-1
├── module-2
│   └── page.tsx      # 模块-2的页面入口文件,访问方式 http://localhost:8080/module-2
├── page.module.css
└── page.tsx          # 项目首页,访问方式 http://localhost:8080

Next.js 与 Umi.js 类似使用的是文件夹为路由系统。每个模块都会有一个模块的布局文件layout.tsx,页面路口文件的协定是文件夹下的page.tsx

页面间的导航

在React技术链中我们常见的路由导航形式是:封装的导航组件、Hooks导航API、最基本的JS路由变更

标签组件导航

Next.js中有默认的模块Link,类似与HTML标签中的a标签,通过href来进行路由跳转

import Link from "next/link";

export default function Model1(){
    return <main>
        <div>Model1</div>
        <Link href='/module-2'>
            点击跳转module-2
        </Link>
    </main>
}

Hooks导航

使用 useRouter的能力来进行导航

'use client'
import { useRouter } from "next/navigation";
import { useCallback } from "react";

export const useModulePath = () => {
    const path = '/module-2';
    const router = useRouter();

    const goToModule2 = useCallback(() => {
        router.push(path)
    }, [router]);

    return { goToModule2 };
}

export const Button = () => {
    const { goToModule2 } = useModulePath()

    return <button onClick={goToModule2} >Hooks 导航--点击跳转module-2</button>
}