[React.js] Props
🤷 Props(Properties) 란?
컴포넌트의 정보를 가지고 있는 객체(Object)이다. 상위 컴퍼넌트가 하위 컴퍼넌트에게 전달하는 용도로 주로 사용된다.(반대는 불가!)
📒 Props 선언 및 표시
JSX의 속성과 같이 선언할 수 있으며, 'this.props.속성명'으로 render() 함수에서 표현 가능하다.
import React from 'react';
import ReactDOM from 'react-dom';
class Greeting extends React.Component {
render() {
return <h1>Hi there, {this.props.firstName}!</h1>; // props 표현
}
}
ReactDOM.render(
<Greeting firstName='Taeng' />, // props firstName 선언
document.getElementById('app')
);
- 다른 모듈에서 컴포넌트를 가져올 때 props 선언
//📂Greeting.js
import React from 'react';
export class Greeting extends React.Component { // export Component
render() {
return <h1>Hi there, {this.props.name}!</h1>; // use props(name)
}
}
//📂App.js
import React from 'react';
import ReactDOM from 'react-dom';
import { Greeting } from './Greeting' // import Component
class App extends React.Component {
render() {
return (
<div>
<h1>
Hullo and, "Welcome to The Newzz," "On Line!"
</h1>
<Greeting name='taeng' /> // use Component with props(name)
<article>
Latest newzz: where is my phone?
</article>
</div>
);
}
}
ReactDOM.render(
<App />,
document.getElementById('app')
);
먼저, Greeting이라는 컴포넌트의 'name' props를 리턴하는 기능을 export 한다.
이후, App.js에서 import를 하고, Greeting을 사용하는 부분에서 'name' props의 값을 부여한다.
- Event Listener를 props 선언하는 경우
단순한 컴포넌트 공유보다는 복잡하므로, 각각의 모듈에 대해 부연설명하겠다.
//📂 Button.js
import React from 'react';
export class Button extends React.Component {
render() {
return (
<button onClick={this.props.onClick}>
Click me!
</button>
);
}
}
Export 모듈: Button 컴포넌트를 내보낸다. <button>의 onClick은 이벤트리스너, {this.props.onClick}은 import 모듈의 onClick props.
//📂 App.js
import React from 'react';
import ReactDOM from 'react-dom';
import { Button } from './Button';
class Talker extends React.Component {
handleClick() {
let speech = '';
for (let i = 0; i < 10000; i++) {
speech += 'blah ';
}
alert(speech);
}
render() {
return <Button onClick={this.handleClick}/>;
}
}
ReactDOM.render(
<Talker />,
document.getElementById('app')
);
Import 모듈: Button을 가져와 Talker 컴포넌트에서 렌더링한다. onClick이라는 props를 받으면 handleClick() 메소드를 리턴한다.
props명(onClick), 메소드명(handleClick) 작성은 자유이나, props명은 이처럼 이벤트와 연관하여 작성하는것이 보편적이다.
📒 this.props.children
모든 컴포넌트에는 children props가 존재한다. 이는, 컴포넌트가 return하는 부모태그 내의 모든 요소를 반환한다.
두 개 이상의 children은 array 형태로 반환하며, <MyComponent /> 처럼 단일태그인 경우엔 undefined를 반환한다.
// 📂 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) { // children 복수 확인
titleText += 's';
}
return (
<div>
<h1>{titleText}</h1>
<ul>{this.props.children}</ul> // children 표현
</div>
);
}
}
Export 모듈: List 컴포넌트를 내보낸다. List JSX의 children이 복수인지(array 형태) 확인, 표현하는 등의 기능이 포함되어 있다.
//📂 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> // children
<li>Harvey Sid Fisher</li> // children
</List>
<List type='Living Cat Musician'>
<li>Nora the Piano Cat</li> // children
</List>
</div>
);
}
}
ReactDOM.render(
<App />,
document.getElementById('app')
);
Import 모듈: 두 개의 List 컴포넌트를 확인할 수 있다. 첫 번째는 children이 2개로, <h1>...Fisher+s</h1>로 표현될 것을 예상할 수 있다.
📒 defaultProps
props를 지정해 놓고, 컴포넌트에 명시하지 않으면 따로 디스플레이가 되지 않는다. 이를 방지하기 위한 default값 설정 properties이다.
import React from 'react';
import ReactDOM from 'react-dom';
class Button extends React.Component {
render() {
return (
<button>
{this.props.text}
</button>
);
}
}
// defaultProps goes here: 선언 없으면 빈 버튼, 선언할 땐 Object 형식 및 key값은 props로!
Button.defaultProps = { text: 'I am a button' };
ReactDOM.render(
<Button />,
document.getElementById('app')
);
이처럼, 클래스 컴포넌트 구문 밑에 default 값을 설정한다. 이는 Object(객체) 형식으로, key 값은 props(여기선 text)로 함을 기억하자.
📌 정리 및 총평
- Passing a prop by giving an attribute to a component instance
- Accessing a passed-in prop via this.props.prop-name
- Displaying a prop
- Using a prop to make decisions about what to display
- Defining an event handler in a component class
- Passing an event handler as a prop
- Receiving a prop event handler and attaching it to an event listener
- Naming event handlers and event handler attributes according to convention
- this.props.children
- getDefaultProps
props 기능 자체는 어렵지 않으나, 이를 선언하는 방법 및 네이밍 등을 헷갈리지 않게 이해하고자 했다.
Export 모듈에서 props를 어떻게 다룰지, Import 모듈에선 props 값을 컴포넌트 태그 안에 작성해야한다.
또, Event Listener과 연관된 props는 props명과 이벤트명을 동일하게 하는 룰을 기억해야겠다.(onClick)