You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Next.js 13中如何隐藏登录与注册页面的导航栏和页脚?

Next.js 13 中隐藏登录/注册页面的导航栏和页脚

方案一:拆分布局组件(推荐)

通过创建不同的布局组件,让需要导航栏的页面嵌套公共布局,登录/注册页面直接使用根布局,结构清晰且扩展性强。

  1. 简化根布局
    修改 app/layout.tsx,只保留页面最基础的容器结构:
export default function RootLayout({
  children,
}: {
  children: React.ReactNode;
}) {
  return (
    <html lang="zh-CN">
      <body>{children}</body>
    </html>
  );
}
  1. 创建带导航栏和页脚的公共布局
    在 app/components/ 目录下新建 LayoutWithNavFooter.tsx:
import Navbar from './Navbar';
import Footer from './Footer';

export default function LayoutWithNavFooter({
  children,
}: {
  children: React.ReactNode;
}) {
  return (
    <>
      <Navbar />
      <main>{children}</main>
      <Footer />
    </>
  );
}
  1. 给需要布局的页面嵌套公共布局
    比如仪表盘页面 app/dashboard/page.tsx:
import LayoutWithNavFooter from '../components/LayoutWithNavFooter';

export default function DashboardPage() {
  return (
    <LayoutWithNavFooter>
      <h1>我的仪表盘</h1>
      {/* 页面内容 */}
    </LayoutWithNavFooter>
  );
}
  1. 登录/注册页面直接渲染内容
    登录页面 app/login/page.tsx 无需嵌套公共布局,直接编写页面内容:
export default function LoginPage() {
  return (
    <div className="login-wrapper">
      <h1>登录账号</h1>
      {/* 登录表单 */}
    </div>
  );
}

方案二:通过路由判断动态隐藏

如果不想拆分布局,可以在根布局里通过当前路径判断,动态显示或隐藏导航栏和页脚。

注意:usePathname 是客户端钩子,需要给根布局加上 'use client' 指令:

'use client';
import { usePathname } from 'next/navigation';
import Navbar from './components/Navbar';
import Footer from './components/Footer';

export default function RootLayout({
  children,
}: {
  children: React.ReactNode;
}) {
  const pathname = usePathname();
  // 定义需要隐藏布局的路径
  const excludePaths = ['/login', '/register'];
  const shouldShowLayout = !excludePaths.includes(pathname);

  return (
    <html lang="zh-CN">
      <body>
        {shouldShowLayout && <Navbar />}
        <main>{children}</main>
        {shouldShowLayout && <Footer />}
      </body>
    </html>
  );
}

方案对比

  • 方案一:结构清晰,适合后续页面布局有差异化需求的场景,扩展性更强。
  • 方案二:实现简单,适合仅需隐藏导航栏/页脚的基础场景。

内容的提问来源于stack exchange,提问作者Rengkat

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.18 14:02:16