-
Image组件
<Image
src="/logo.svg"
width={50}
height={50}
alt="Logo"
/>
- Image 组件来自 Next.js,默认开启懒加载
width 和 height 是 required
src 可以是 internal path 或者 external url,使用 external url 时需要在 next.config.js 文件中配置 remotePatterns
import type { NextConfig } from "next";
const nextConfig: NextConfig = {
images: {
remotePatterns: [
{
protocol: 'https',
hostname: 'szxu79mai4.ufs.sh'
}
]
}
};
export default nextConfig;
-
修改字体 src/app/layout.tsx
- 删除原有字体,导入新字体
import { Inter } from "next/font/google";,并修改 <body>的className
...
import { Inter } from "next/font/google";
...
const inter = Inter({ subsets: ["latin"] });
export const metadata: Metadata = {
title: "New Tube",
description: "New Tube",
};
export default function RootLayout({
children,
}: Readonly<{
children: React.ReactNode;
}>) {
return (
<html lang="en">
<body
className={ inter.className }
>
{children}
</body>
</html>
);
}
-
App Router folders
- Next.js 15 使用
app/ 目录结构创建路由,路由基于文件夹结构自动生成
src/
app/
page.tsx
layout.tsx
home/
page.tsx
videos/
[videoId]/
page.tsx
interface VideoIdPageProps{
params: Promise<{ videoId: string }>;
}
const Page = async ({ params }: VideoIdPageProps) => {
const { videoId } = await params;
return (
<div>
video ID: { videoId }
</div>
)
}
export default Page;
-
Layout.tsx
- 在 App Router 中用于构建页面布局的组件,通常也用于创建可重用的布局(导航、侧边栏等),所以所有子页面会嵌套在 layout.tsx 的结构中
- 子文件夹可以有自己的 layout.tsx
- 如下目录结构中,会先渲染 app/layout.tsx,再渲染 app/videos/layout.tsx
- 必须包含
children 作为插槽,children 是页面内容
src/
app/
page.tsx
layout.tsx
videos/
page.tsx
layout.tsx
[videoId]/
page.tsx
interface LayoutProps {
children: React.ReactNode;
}
const Layout = ({ children }: LayoutProps) => {
return (
<div>
<div className="p-4 bg-red-300 w-full">
this is a navbar
</div>
{ children }
</div>
)
}
export default Layout;
-
Route Groups
src/
app/
layout.tsx
(home)/
layout.tsx
page.tsx
modules/
home/
ui/
layouts/
home-layout.tsx
-
关于项目结构
- 基于上面的目录,app 文件夹中只放置 route 相关的文件
- 其他components、hooks、apis、server、utils等等都将放在 modules 文件夹下
-
Sidebar组件
SidebarProvider 是根级组件,用于提供侧边栏的上下文
- 将其他组件写在
SidebarProvider 内部,保证这些组件都能访问到其提供的有关状态