Elements
Elements는 React app의 최소 단위이다. Element와 Component를 혼동해서는 안된다. Component는 Elements(요소들)로 이루어 진다.
Components
Components는 UI를 독립적으로 나눌 수 있게하고, 코드 재사용을 통해 생산성을 높힌다. 잘 할때 말이지… Components는 Javascript function과 비슷하다. 또한 임의의 입력값을 받을 수 있으며 이 입력값은 “props”라 부른다. 그리고 Elements가 어떻게 화면에서 나타날지 return한다.
Components를 만드는 방법은 Function / Class 두 가지 방법이 있다.
- function type
1 2 3
function Welcome(props) { return <h1>Hello, {props.name}</h1>; }
- class type
1 2 3 4 5
class Welcome extends React.Component { render() { return <h1>Hello, {this.props.name}</h1>; } }
우리가 정의한 Component를 Element로 표현할 때, 이 Element는 JSX attributes, 또는 children(Single object)를 넘겨 받을 수 있다. 이것을 우리는 “props”라고 부른다.
1
2
3
4
5
6
7
8
9
function Welcome(props) {
return <h1>Hello, {props.name}</h1>;
}
const element = <Welcome name="Roy" />;
ReactDOM.render(
element,
document.getElementById('root')
);
주의: Component name은 항상 대문자로 시작해야 한다. 소문자로 시작하면 DOM tag로 인식한다.
Props
props는 Read-Only다. 아래의 코드를 보자.
1
2
3
function sum(a, b) {
return a + b;
}
sum 함수는 “pure” 하다. “pure” 한 함수는 input을 변경하지 않는다. 그리고 같은 input값에 대해서 항상 같은 output값을 가진다.
모든 React Components는 반드시 props에 대해서 “pure function” 과 같이 동작해야 한다.
물론 Components 내부에서 동적인 동작이 필요할 때가 있을 것이다. React에서는 그런 동작을 위해 “state”를 사용한다. 이건 내일 정리해야겠다.