简体   繁体   中英

How “props.children” works on a React component?

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 component start holding other components the Navbar component still appears

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

What happens behind the scenes?

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

For ex, if u put a div block between Layout components, 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>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM