next.js 如何在下一个js 13中使用上下文并仍然使用元数据API

ki1q1bka  于 2023-06-22  发布在  其他
关注(0)|答案(2)|浏览(150)

我无法使用默认主题呈现layout.tsx,因为需要主题提供程序并调用useContext。因此,next js抱怨无法运行服务器端。所以我将use client字段放入文档中,现在元数据标记将无法加载。
layout.tsx

'use client'

import { Metadata } from 'next'
export const metadata: Metadata = {
  title: {
    default: 'some title',
    template: '%s | some title'
  }
}

import { createTheme, ThemeProvider } from '@mui/material/styles'
const theme = createTheme({...

export default ({children}: {children: React.ReactNode}) => (

    <ThemeProvider theme={theme}>
        <LocalizationProvider dateAdapter={AdapterDayjs}>
            <html>
                <body>{children}</body>
            </html>
        </LocalizationProvider>
    </ThemeProvider>
)
pxyaymoc

pxyaymoc1#

不要让布局成为客户端组件,而是创建一个名为Provider的客户端组件,然后可以将其导入布局中。下面是一个例子:

"use client";

import { createTheme, ThemeProvider } from '@mui/material/styles'

interface Props extends React.PropsWithChildren {}

const theme = createTheme(/* ... */);

export default function Provider({ children }: Props) {
  return <ThemeProvider>{ children }</ThemeProvider>;
}
pvcm50d1

pvcm50d12#

你需要将它们分成两个文件,一个客户端和另一个服务器
Layout.tsx

import { Metadata } from 'next'

import RootLayout from './RootLayout'

export const metadata: Metadata = {
  title: {
    default: 'some title',
    template: '%s | some title'
  }
}

export default function Layout({ children }: LayoutProps) {
    return (
        <html lang="en">
            <body>
                <RootLayout>{children}</RootLayout>
            </body>
        </html>
    )
}

RootLayout.tsx

'use client'

import { createTheme, ThemeProvider } from '@mui/material/styles'
const theme = createTheme({})

export default RootLayout({children}: {children: React.ReactNode}) => (

    <ThemeProvider theme={theme}>
        <LocalizationProvider dateAdapter={AdapterDayjs}>
            <html>
                <body>{children}</body>
            </html>
        </LocalizationProvider>
    </ThemeProvider>
)

相关问题