在Next.js 13中应该把提供程序放在哪里?

huangapple go评论59阅读模式
英文:

Where to put providers in NextJs 13?

问题

我正在使用Mui的日期库,它要求在所有组件周围包装一个提供者:

import { LocalizationProvider } from '@mui/x-date-pickers';
import { AdapterDayjs } from '@mui/x-date-pickers/AdapterDayjs';

function App({ children }) {
  return (
    <LocalizationProvider dateAdapter={AdapterDayjs}>
      {children}
    </LocalizationProvider>
  );
}

但在只提供/app目录中的页面的NextJs 13中,没有对应的App函数。

英文:

I'm using the date library by Mui and it requires a provider to be wrapped around all components:

import { LocalizationProvider } from &#39;@mui/x-date-pickers&#39;;
import { AdapterDayjs } from &#39;@mui/x-date-pickers/AdapterDayjs&#39;

function App({ children }) {
  return (
    &lt;LocalizationProvider dateAdapter={AdapterDayjs}&gt;
      {children}
    &lt;/LocalizationProvider&gt;
  );
}

But there's no corresponding App function in NextJs 13 which only offers pages in the /app directory.

答案1

得分: 1

在Next.js 13中,App函数被替换为位于app目录中的根布局。您可以将提供程序包装在app/layout.tsx文件中的所有组件周围:

import { LocalizationProvider } from '@mui/x-date-pickers';
import { AdapterDayjs } from '@mui/x-date-pickers/AdapterDayjs';

export default function RootLayout({
  children,
}: {
  children: React.ReactNode;
}) {
  return (
    <LocalizationProvider dateAdapter={AdapterDayjs}>
      <html lang="en">
        <body>{children}</body>
      </html>
    </LocalizationProvider>
  );
}

这将将LocalizationProvider应用于app内部的所有路由。children属性将填充嵌套布局或页面。

英文:

In Next.js 13, the App function is replaced by the root layout in the app directory. You can wrap your provider around all components in the app/layout.tsx file:

import { LocalizationProvider } from &#39;@mui/x-date-pickers&#39;;
import { AdapterDayjs } from &#39;@mui/x-date-pickers/AdapterDayjs&#39;

export default function RootLayout({
  children,
}: {
  children: React.ReactNode
}) {
  return (
    &lt;LocalizationProvider dateAdapter={AdapterDayjs}&gt;
      &lt;html lang=&quot;en&quot;&gt;
        &lt;body&gt;{children}&lt;/body&gt;
      &lt;/html&gt;
    &lt;/LocalizationProvider&gt;
  )
}

This will apply the LocalizationProvider to all routes inside app. The children prop will be populated with nested layouts or pages

huangapple
  • 本文由 发表于 2023年7月10日 20:17:37
  • 转载请务必保留本文链接:https://go.coder-hub.com/76653664.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定