23 Temmuz 2019 Salı

React props.children

Giriş
Açıklaması şöyle. Bileşenin açma ve kapama tag'leri arasındaki şeyler props.children olarak gelir.
What is ‘props.children’?
The React docs say that you can use props.children on components that represent ‘generic boxes’ and that don’t know their children ahead of time. For me, that didn’t really clear things up. I’m sure for some, that definition makes perfect sense but it didn’t for me.
My simple explanation of what this.props.children does is that it is used to display whatever you include between the opening and closing tags when invoking a component.
Örnek
Elimizde şöyle bir bileşen olsun.
function Layout(props) {
  return(
    <React.Fragment>
      <Navbar />
      {props.children}
    </React.Fragment>
  );
}
Şöyle yaparız.
<Layout>
  <Switch>
    <Route exact path="/badges" component={Badges}/>
    <Route exact path="/badges/new" component={BadgeNew} />
  </Switch>
</Layout>
Örnek
Elimizde şöyle bir bileşen olsun.
const Picture = (props) => {
  return (
    <div>
      <img src={props.src}/>
      {props.children}
    </div>
  )
}
Şöyle yaparız
//App.js
render () {
  return (
    <div className='container'>
      <Picture key={picture.id} src={picture.src}>
          //what is placed here is passed as props.children  
      </Picture>
    </div>
  )
}

Hiç yorum yok:

Yorum Gönder