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

Next.js 13 app目录下如何从page.js向layout.js传递props?

Next.js 13 中向 Layout 传递数据的方案

在 Next.js 13 的 App Router 体系下,原生的 layout.js 无法直接从对应的 page.js 接收 props——因为 Layout 属于路由层级的框架控制组件,Page 是它的子节点,不存在反向传参的机制。不过我们有几种更优的替代方案:

方案1:利用路由元数据(Metadata)

如果要传递的内容是页面标题这类和元数据相关的信息,可以直接在 Page 中定义元数据,Layout 里通过 useMetadata 读取:

// page.js
export const metadata = {
  title: "我的页面标题"
};

export default function Page() {
  return <div>页面内容</div>;
}
// layout.js
import { useMetadata } from 'next/navigation';

export default function Layout({ children }) {
  const metadata = useMetadata();
  return (
    <>
      <h1>{metadata.title}</h1>
      {children}
    </>
  );
}

方案2:使用 React Context

如果需要传递复杂数据,或者数据和元数据无关,可以通过 Context 实现跨层级传递:

// LayoutContext.js
'use client';
import { createContext, useContext } from 'react';

const LayoutContext = createContext(null);

export function LayoutProvider({ children, text }) {
  return (
    <LayoutContext.Provider value={{ text }}>
      {children}
    </LayoutContext.Provider>
  );
}

export function useLayoutContext() {
  return useContext(LayoutContext);
}
// page.js
import { LayoutProvider } from './LayoutContext';

export default function Page() {
  return (
    <LayoutProvider text="我的页面自定义文本">
      <div>页面内容</div>
    </LayoutProvider>
  );
}
// layout.js
import { useLayoutContext } from './LayoutContext';

export default function Layout({ children }) {
  const { text } = useLayoutContext();
  return (
    <>
      <h1>{text}</h1>
      {children}
    </>
  );
}

方案3:基于路由路径匹配

如果每个路由页面对应的文本是固定的,可以在 Layout 中通过路由路径直接匹配:

// layout.js
'use client';
import { usePathname } from 'next/navigation';

export default function Layout({ children }) {
  const pathname = usePathname();
  // 配置路由路径与文本的映射
  const textMap = {
    '/': '首页',
    '/about': '关于我们',
    '/blog': '博客专栏'
  };
  const text = textMap[pathname] || '默认标题';

  return (
    <>
      <h1>{text}</h1>
      {children}
    </>
  );
}

关于你当前的实现

你现在用自定义 Layout 组件嵌套的方式完全可行,适合需要给每个 Page 灵活配置不同 props 的场景——如果没有复杂数据或全局复用需求,这种方式反而更直观。

内容的提问来源于stack exchange,提问作者Pedro Sánchez

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.03 22:40:32