【发布时间】:2022-01-23 21:25:12
【问题描述】:
我有两个 nextjs 布局
主布局
import Navigation from '../Navigation';
export default function MainLayout({ children }) {
return (
<>
<Navigation
links={[
{
href: '/about',
label: 'About'
},
{
href: '/contact-us',
label: 'Contact'
},
{
href: '/faq',
label: 'FAQ'
},
{
href: '/dashboard',
label: 'Dashboard'
}
]}
/>
{children}
</>
)
}
和仪表板布局
import Sidebar from '../Dashboard/Sidebar';
import Navigation from '../Dashboard/Navigation';
export default function DashboardLayout({ children }) {
return (
<>
<Sidebar />
<div className="lg:ml-64">
<Navigation />
{children}
</div>
</>
)
}
我的 _app.js 中有以下内容
import Head from 'next/head';
import { Provider } from 'next-auth/client';
// assets
import '../styles/global.css';
import '../javascripts/app.js';
// components
import MainLayout from './components/Layouts/MainLayout';
import DashboardLayout from './components/Layouts/DashboardLayout';
import Footer from './components/Footer';
function MyApp({ Component, pageProps }) {
const Layout = Component.MainLayout || DashboardLayout;
return (
<>
<Head>
<meta name="theme-color" content="#1E40AF" />
</Head>
<section className="flex flex-col min-h-screen">
<Provider session={pageProps.session}>
<Layout>
<Component {...pageProps} className="flex-1" />
</Layout>
</Provider>
</section>
<Footer />
</>
);
}
const MainLayout = ({ children }) => <>{children}</>;
const DashboardLayout = ({ children }) => <>{children}</>;
export default MyApp;
在主索引文件 [homepage] 我将以下内容放在底部
export default function Home() {
... content
};
Home.Layout = MainLayout;
所以理论上这个页面应该使用 MainLayout,但是,我得到了以下错误
Module parse failed: Identifier 'MainLayout' has already been declared
我在这里做错了什么,我希望能够告诉每个页面使用什么布局?
【问题讨论】:
-
在您的
_app.js中,您正在导入MainLayout,但在该文件的底部附近,您还声明了一个具有相同名称的const。我认为这是你错误的根源。如果要导入布局,是否需要在底部声明这两个常量? -
不走运@Hughes,检查似乎有导入但其他人不导入的文档我也看过这个视频youtube.com/watch?v=69-mnojSa0M
-
正如@Hughes 所说,您不需要在
_app中导入MainLayout,也不需要在@ 底部重新声明MainLayout和DashboardLayout987654334@ 文件(这就是导致错误的原因)。您还应该在_app中定位Component.Layout,因为这就是您在页面中所称的,即const Layout = Component.Layout || DashboardLayout;
标签: javascript reactjs next.js