最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - How "props.children" works on a React component? - Stack Overflow

programmeradmin11浏览0评论

I was working on the code of a practice for React, but I stopped because I have to make a navigation bar be shared among other pages

I found the next solution and it works but I don't know how exactly works; this is for a course project.

function Layout(props) {
  return(
    <React.Fragment>
      <Navbar />
      {props.children}
    </React.Fragment>
  );
}

I can't really know what really {props.children} does and how if Layout ponent start holding other ponents the Navbar ponent still appears

<Layout>
  <Switch>
    <Route exact path="/badges" ponent={Badges}/>
    <Route exact path="/badges/new" ponent={BadgeNew} />
  </Switch>
</Layout>

What happens behind the scenes?

I was working on the code of a practice for React, but I stopped because I have to make a navigation bar be shared among other pages

I found the next solution and it works but I don't know how exactly works; this is for a course project.

function Layout(props) {
  return(
    <React.Fragment>
      <Navbar />
      {props.children}
    </React.Fragment>
  );
}

I can't really know what really {props.children} does and how if Layout ponent start holding other ponents the Navbar ponent still appears

<Layout>
  <Switch>
    <Route exact path="/badges" ponent={Badges}/>
    <Route exact path="/badges/new" ponent={BadgeNew} />
  </Switch>
</Layout>

What happens behind the scenes?

Share Improve this question edited Jul 24, 2019 at 7:58 wuarmin 4,0254 gold badges20 silver badges37 bronze badges asked Jul 24, 2019 at 4:25 Pablo VerduzcoPablo Verduzco 1212 silver badges11 bronze badges
Add a ment  | 

2 Answers 2

Reset to default 7

props.children means that React will render whatever u put between Layout ponent.

For ex, if u put a div block between Layout ponents, props.children will be that div.

Every JSX code that you put inside the Layout-tag, will be placed in children property of props-object of the Layout Component.

<Layout>
  <div>this is a child</div>
  <AnotherReactComponentAsLayoutChild/>
</Layout>
发布评论

评论列表(0)

  1. 暂无评论