Nextjs:如何< header>根据加载的组件动态设置内容

pnwntuvh  于 9个月前  发布在  其他
关注(0)|答案(2)|浏览(117)

我创建了一个app/components/Header.js组件。

export function Header() {
    return <>
    <header className="w-full h-14 grid grid-cols-12 bg-gray-50 text-black dark:bg-gray-900 dark:text-white">
        <div className="left self-center col-span-3">
            <div className="logo text-black dark:text-white ml-6 text-xl">
                <a href="#">Logo</a>
            </div>
        </div>
        <div className="center self-center col-span-6 text-center">
            <p>{ set dynamic title here}</p>
        </div>
        <div className="right self-center col-span-3 text-right mr-6">
            <div className="CTA">
                <a className="" href="#">CTA</a>
            </div>
        </div>
    </header>
    </>
}

字符串
这是app/layout.js

import { Roboto } from "next/font/google";
import { Header } from "./components/Header";
import { Footer } from "./components/Footer";

import './globals.css'

const roboto = Roboto({subsets: ["latin"], weight: ["400", "700"]})

export const metadata = {
  title: {
    default: "Index",
    template: "%s | Sitename"
  },
  description: 'Abcdef.',
}

export default function RootLayout({children}) {
  return (
    <html lang="en">
      <body className={roboto.className}>
        <Header/>
        {children}
        <Footer/>
      </body>
    </html>
  )
}


这是app/samad/page.js

export const metadata = {
    title: "Samad"
}

export default function Samad(){
    return <>
        <h1>Hello, THis is samad</h1>    
    </>
}


每当我打开http://localhost:3000/samad时,<header>中的标题内容应该更改为“samad”。
我到处都找过了,有点混乱。
我尝试使用useState()并将RootLayout导入到page.js,但导致错误,因为我们不能在server-components中使用useState()。如果我将其设置为client-component,则无法使用metadata
我也使用document.title,但错误:文档未找到。
注意:文档标题(标签标题)正在更改。我想更新<Header>中的内容

6rvt4ljy

6rvt4ljy1#

我认为你需要在所有子组件中使用Header组件而不是RootLayout,并向Header组件添加title属性:

export function Header({title}) {
    return <>
    <header className="w-full h-14 grid grid-cols-12 bg-gray-50 text-black dark:bg-gray-900 dark:text-white">
        <div className="left self-center col-span-3">
            <div className="logo text-black dark:text-white ml-6 text-xl">
                <a href="#">Logo</a>
            </div>
        </div>
        <div className="center self-center col-span-6 text-center">
            <p>{title}</p>
        </div>
        <div className="right self-center col-span-3 text-right mr-6">
            <div className="CTA">
                <a className="" href="#">CTA</a>
            </div>
        </div>
    </header>
    </>
}

个字符

moiiocjp

moiiocjp2#

将其添加到同一页面的layout.js中。这就是next/layout的作用。

相关问题