Next.js 条件布局

Gur*_*eer 3 next.js

我已更改 _app.js 以根据加载的页面加载布局。在开发模式下一切正常,但一旦我创建构建,它就无法获取“Component.name”并返回空值。请问有什么建议吗?

我的_app.js

import "../styles/globals.css";
import Layout from "../components/Layout";

function MyApp({ Component, pageProps }) {
  switch (Component.name) {
    case "Home":
      return <Component {...pageProps} />;
    default:
      return (
        <Layout>
          <Component {...pageProps} />{" "}
        </Layout>
      );
  }
}

export default MyApp;
Run Code Online (Sandbox Code Playgroud)

Dan*_*ila 5

name为空,因为代码缩小会删除这些值或混淆它们,因此您不应依赖类或函数的名称。

对于每页布局,请遵循此官方指南

基本上,您为每个页面创建getLayout函数,该函数应该返回布局:

import Layout from '../components/layout'
import NestedLayout from '../components/nested-layout'

export default function Page() {
  return {
    /** Your content */
  }
}

Page.getLayout = function getLayout(page) {
  return (
    <Layout>
      <NestedLayout>{page}</NestedLayout>
    </Layout>
  )
}
Run Code Online (Sandbox Code Playgroud)

_app这样使用它:

export default function MyApp({ Component, pageProps }) {
  // Use the layout defined at the page level, if available
  const getLayout = Component.getLayout || ((page) => page)

  return getLayout(<Component {...pageProps} />)
}
Run Code Online (Sandbox Code Playgroud)