
import React, { Component } from 'react';
import SubClass from './components/SubClass';
class App extends Component { render() {
return (
<div className="App">
<SubClass>여기에 적은 Text가 children에 들어간다~ <br/>
<strong>아하하하</strong>
</SubClass>
</div>
);
}}export default App;
const SubClass = ({ children }) => {
return (
<div className="todos-wrapper">
{children}
</div>
);
};
export default SubClass;
예시 코드를 보자. Subclass 컴포넌트는 Props로 children을 받고 있다. Props.children이지만 비구조할당을 통해 {children}이라고 써준다. Subclass는 <div className="todos-wrapper"></div>로 children을 감싸고 있다. 그럼 감싸진 children은?
<SubClass>여기에 적은 Text가 children에 들어간다~ <br/>
<strong>아하하하</strong>
</SubClass>
위의 App 컴포넌트에 보면 SubClass 컴포넌트가 임포트 되어 있고, 그 안에 여기에 적은 Text가 children에 들어간다~ <br/> <strong>아하하하</strong>가 끼어있는데 이게 children 내용이 된다.
즉, 부모는 자식에게 간섭할 수 있다는걸 생각하면 된다.
그러면 컴포넌트로 감싸진 모든게 children 인가요?
정답은 아니다. 자식이 있으면 자손도 있는 법.
const li_Array = ["First item.", "Second item."];
const App = () => (
<Category>
<ul>
{li_Array.map((value, idx) => (
<li key={idx}>{value}</li>
))}
</ul>
</Category>
);
이 코드는 <ul> 태그안에 <li> 태그가 2개 생성되는 코드다. <li>는 카테고리 컴포넌트의 자손에 해당한다. 이를 알 수 있는 방법은 해당 컴포넌트의 자식 숫자를 알려주는 함수가 있다.
class Category extends React.Component {
render() {
console.log("자식의 수 : " + React.Children.count(this.props.children));
return <React.Fragment>{this.props.children}</React.Fragment>;
}
}
그러면 자식의 수가 1개로 나온다.