将 props 从根布局传递给 page.jsx 子级 (next.js 13)

Viv*_*mar 20 reactjs server-side-rendering next.js next.js13

如何将 props 传递给布局的 page.jsx ?(下13)

//app/blog/layout.jsx

export default function RootLayout({ children }) {
  return (
    <div>
      <Navbar />
      <Sidebar />
      {/*How do I pass any props from this root layout to this {children} that Im getting from page.jsx*/}
      {children}
    </div>
  );
}
Run Code Online (Sandbox Code Playgroud)

基本上,如何将 prop 传递给函数 prop(Next.JS 13)?

Yil*_*maz 13

根据next13 文档,您不能:

无法在父布局与其子布局之间传递数据。但是,您可以在一个路由中多次获取相同的数据,React 会自动删除请求的重复数据,而不会影响性能。

因为布局组件是指定义应用程序或 UI 特定部分内其他组件的整体结构和排列的组件。它不是为了实现状态管理而设计的。其全部目的是减少首次渲染的时间以增加用户体验

但我找到了办法。在Rootlayoutconsole.log(props)

export default function RootLayout(props) {
  console.log("props in layout",props)
  return (
        <div>
          {props.children}
        </div>
  );}
Run Code Online (Sandbox Code Playgroud)

这就是你将看到的

props in layout {
  children: {
    '$$typeof': Symbol(react.element),
    type: {
      '$$typeof': Symbol(react.module.reference),
      filepath: '/home/tesla//node_modules/next/dist/client/components/layout-router.js',
      name: '',
      async: false
    },
    key: null,
    ref: null,
    props: {
      parallelRouterKey: 'children',
      segmentPath: [Array],
      error: undefined,
      errorStyles: undefined,
      loading: undefined,
      loadingStyles: undefined,
      hasLoading: false,
      template: [Object],
      templateStyles: undefined,
      notFound: [Object],
      notFoundStyles: undefined,
      childProp: [Object],
      rootLayoutIncluded: true
    },
    _owner: null,
    _store: {}
  },
  // THIS IS HOW WE PASS PROPS
  params: {}
}
Run Code Online (Sandbox Code Playgroud)

许多属性不可扩展,但params. 我们可以动态地向这个对象添加属性。例如

     props.params.newProp = "testing";
Run Code Online (Sandbox Code Playgroud)

现在访问page.js

const Page = (props) => {
  console.log("props in page", props);
  return ()}
Run Code Online (Sandbox Code Playgroud)

你会看到 props 被添加到params对象中

在此输入图像描述

无论我尝试什么,page.tsx只有两个道具:paramssearchParamssearchParams如果 url 上有查询参数,则会自动填充。所以,我认为params这是从根布局传递道具的唯一方法。你也可以传递函数

  • 我懂了。根据 [Next.js 文档](https://beta.nextjs.org/docs/routing/pages-and-layouts#layouts),不可能在父布局与其子布局之间传递数据。但是您在答案中提到的是一个有趣的发现,不知道您可以扩展“params”对象并使道具可用于布局的子项。 (2认同)