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

如何在Next.js中将getStaticProps的Props传递给Layout组件?

解决方法

在Next.js Pages Router模式下,getLayout函数支持接收第二个参数——也就是getStaticProps/getServerSideProps返回的页面props,只需调整getLayout的定义即可将props传递给Layout组件:

  • 修改页面组件的getLayout函数,新增props参数并传递给Layout:
Home.getLayout = function getLayout(page, props) {
  return <Layout {...props}>{page}</Layout>;
};
  • 确保Layout组件能接收并使用这些props,示例如下:
// layouts/Layout.js
export default function Layout({ title, children }) {
  return (
    <div>
      <header>页面标题:{title}</header>
      <main>{children}</main>
    </div>
  );
}
  • (可选)若页面组件自身需要使用props,记得在Home组件中接收:
export default function Home(props) {
  // 此处可直接使用props.title
  return (
    <>
      <div className="m-5">
        <div className="bg-white h-[400px] flex justify-center items-center text-4xl">
          Welcome to Dashboard
        </div>
      </div>
    </>
  );
}

这样getStaticProps返回的title就能正常传递到Layout组件中使用了。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.26 07:42:42