我创建了接下来的 13 个项目,其中包含许多子页面。 在接下来的 13 中,我找到了使用应用程序文件夹中的文件夹(如
app/contact/page.tsx
)执行此操作的SOLOUTIN
我尝试了一下,它有效,所以我可以使用 localhost:3000/contact 打开路由
现在我想更改子页面的元标题,但存在问题......
我无法添加:
import type { Metadata } from 'next'
export const metadata: Metadata = {
title: 'Home | Sakura Hagen',
description: 'Home Page of Sakura Hagen',
}
因为我在我的子页面中使用“使用客户端”,所以这就是我尝试过的其他方法。
首先我尝试像这样导入头:
import Head from 'next/head';
return (
<>
<Head>
<title>Contact - Page </title>
<meta name="description" content="Willkommen zu meinem Blog" />
</Head>....
但这并没有改变什么。结果还是之前的标题。
接下来我尝试
npm i next-seo
然后我尝试像这样导入它
import { NextSeo } from 'next-seo';
<NextSeo
title="Contact - Page"
description="description"
/>
但一切都没有改变...
最后我尝试创建一个layout.tsx,我在其中添加如下元数据:
import { Footer, Navbar, ScrollToTop, Tel } from '@/components'
import './globals.css'
import type { Metadata } from 'next'
import { Inter } from 'next/font/google'
const inter = Inter({ subsets: ['latin'] })
export const metadata: Metadata = {
title: 'contact - page',
description: 'description',
}
export default function RootLayout({
children,
}: {
children: React.ReactNode
}) {
return (
<html lang="de" className='scroll-smooth'>
<body className="relative">
<Navbar />
{children}
<Footer />
<Tel />
<ScrollToTop />
</body>
</html>
)
}
它有点作用,如果我打开我的主页并单击“联系”,我会转到.../联系新标题。但如果我尝试跳回主页,错误看起来像这样。
Unhandled Runtime Error
NotFoundError: Failed to execute 'removeChild' on 'Node': The node to be removed is not a child of this node.
我在制定它时已经找到了答案,我希望它对其他人有帮助
非常简单...
只需使用:
<title>Page title</title>
页面内部.tsx
应该看起来像这样
import React from 'react'
const page = () => {
return (
<title>Page title</title>
<div>page</div>
)
}
export default page
由于您使用的是 App Router,因此无需手动使用
<title>
元素。如果您查看有关元数据的Next.js 文档,您会注意到沿段进行了合并。
例如,在我位于
app/layout.tsx
的根布局中,我声明以下内容:
export const metadata = {
title: {
template: '%s — Showcasething'
}
}
在页面内,例如
app/page.tsx
,我可以执行以下操作:
export const metadata = {
title: 'Page Title'
}
Next.js 的作用是合并这些导出的
metadata
对象(或从 generateMetadata
生成的元数据)以构建最终的元数据,从而构建标题。在我的示例中,导航到 /
处的根路径将采用根布局的模板和页面特定标题“页面标题”中的插槽,从而生成“页面标题 - Showcasething”。
当然,在没有模板的情况下,只需使用分段上的
title
来覆盖它们(如果适用)即可实现相同的效果。另一个例子:
// app/layout.tsx
export const metadata = {
title: 'Home'
}
// app/nested/page.tsx
export const metadata = {
title: 'Nested'
}
此配置将使
/nested
的标题变为“Nested”。