【问题标题】:Pass props to page.jsx child from root layout (next.js 13)将道具从根布局传递给 page.jsx 子级 (next.js 13)
【发布时间】:2022-11-27 02:56:56
【问题描述】:

你如何将道具传递给布局的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>
  );
}

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

【问题讨论】:

    标签: reactjs next.js


    【解决方案1】:

    如果你想将这个孩子的道具发送到 Navbar 组件

    <Navbar children = {children} />
    

    【讨论】:

    • 不,我在根布局中有一个变量,我想与传递给根布局的 {children} 共享。不是导航栏
    • 你能在你有那个变量的地方显示代码吗
    【解决方案2】:

    Rootlayoutconsole.log(props)

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

    这就是你会看到的

    props in layout {
      children: {
        '$$typeof': Symbol(react.element),
        type: {
          '$$typeof': Symbol(react.module.reference),
          filepath: '/home/tesla/Documents/projects/next.js/youtube-next13-static-blog/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: {}
    }
    

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

         props.params.newProp = "testing";
    

    现在访问page.js

    const Page = (props) => {
      console.log("props in page", props);
      return ()}
    

    你会看到道具被添加到params对象

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2023-01-13
      • 1970-01-01
      • 2018-10-10
      • 2017-12-24
      • 2019-10-16
      • 2018-08-25
      • 2015-08-12
      相关资源
      最近更新 更多