如何在Next 13应用程序文件夹的根布局中使用上下文?

omqzjyyz  于 2023-05-17  发布在  其他
关注(0)|答案(1)|浏览(87)

我想使用我的全局主题来样式化下一个13个新应用程序文件夹的RootLayout中的主体。如何在根布局中使用上下文?

import './globals.css'
import { Inter } from 'next/font/google'

import ThemeProvider from "./hooks/theme"
import CardsProvider from "./hooks/getCards"

const inter = Inter({ subsets: ['latin'] })

export const metadata = {
  title: 'Create Next App',
  description: 'Generated by create next app',
}

export default function RootLayout({
  children,
}: {
  children: React.ReactNode
}) {
  return (
    <html lang="en">
      <body className={inter.className}>
        <ThemeProvider>
            <CardsProvider>
              {children}
            </CardsProvider>
        </ThemeProvider>
      </body>
    </html>
  )
}
lsmd5eda

lsmd5eda1#

您可以尝试创建一个客户端组件ParentWrapper来 Package 所有上下文提供程序。
例如-
app/ParentWrapper.tsx

"use client";
import React from "react";

import ThemeProvider from "./hooks/theme"
import CardsProvider from "./hooks/getCards"

export default function ParentProvider({
    children
}: {
    children: React.ReactNode
}) {
    return (
        <ThemeProvider>
            <CardsProvider>
                {children}
            </CardsProvider>
        </ThemeProvider>
    )
}

然后在RootLayout中使用该组件。
app/RootLayout.tsx

import './globals.css'
import { Inter } from 'next/font/google'
import ParentProvider from './ParentProvider';

const inter = Inter({ subsets: ['latin'] })

export const metadata = {
  title: 'Create Next App',
  description: 'Generated by create next app',
}

export default function RootLayout({
  children,
}: {
  children: React.ReactNode
}) {
  return (
    <html lang="en">
      <body className={inter.className}>
        <ParentProvider>
          {children}
        </ParentProvider>
      </body>
    </html>
  )
}

相关问题