Study/React

this.props.children

더 멋진 세상을 꿈꾸는 개발자 2020. 5. 27. 13:25

this.props.children

 

모든 컴포넌트의 props 객체는 children이라고 이름된 property를 가진다. 

 

this.props.children은 컴포넌트의 오프닝과 JSX태그들 클로징 사이에서 모든것을 리턴할 것이다. 

 

지금까지, <MyComponentClass />같이 당신이 봐온 모든 컴포넌트들은  self-closing tag들이었다. 

그들은 그럴필요는 없다!

당신은 <MyComponentClass></MyComponentClass> 라고 적을수도 있고, 이것은 여전히 동작할 것이다. 

 

this.props.children은 <MyComponentClass></MyComponentClass>사이에서 모든것들을 리턴할것이다.

 

BigButton.js를 보자.

Example1에서 <BigButton>의 this.props.children은  “I am a child of BigButton.” 텍스트와 같다.

Example2에서 <BigButton>의 this.props.children은 <LilButton />컴포넌트와 같다. 

Example3에서 <BigButton>의 this.props.children는 undefined와 같다. 

 

만약 컴포넌트가 JSX태그들 사이의 한 child보다 더 많이 가진다면 

this.props.children는 children들을 배열에 담아 리턴할 것이다. 

 

그러나 , 만약 컴포넌트가 오직 한 child만 가진다면, 

this.props.children는 배열에 담지 않고 한 child만 리턴할 것이다. 

 

 

import React from 'react';
import { LilButton } from './LilButton';

class BigButton extends React.Component {
  render() {
    console.log(this.props.children);
    return <button>Yo I am big</button>;
  }
}


// Example 1
<BigButton>
  I am a child of BigButton.
</BigButton>


// Example 2
<BigButton>
  <LilButton />
</BigButton>


// Example 3
<BigButton />

 

 

 

// child갯수에 따라 자동적으로 title 바꾸는 방법

 

//List.js

import React from 'react';

export class List extends React.Component {
  render() {
    let titleText = `Favorite ${this.props.type}`;
    if (this.props.children instanceof Array) {
    	titleText += 's';
    }
    return (
      <div>
        <h1>{titleText}</h1>
        <ul>{this.props.children}</ul>
      </div>
    );
  }
}
// App.js

import React from 'react';
import ReactDOM from 'react-dom';
import { List } from './List';

class App extends React.Component {
  render() {
    return (
      <div>
        <List type='Living Musician'>
          <li>Sachiko M</li>
          <li>Harvey Sid Fisher</li>
        </List>
        <List type='Living Cat Musician'>
          <li>Nora the Piano Cat</li>
        </List>
      </div>
    );
  }
}

ReactDOM.render(
  <App />, 
  document.getElementById('app')
);