컴포넌트의 속성값 으로, 부모 컴포넌트로부터 전달 받은 데이터를 지니고 있는 객체 이다.
props
를 통해 부모 컴포넌트로부터 자식 컴포넌트에게 state
상태 값, event handler
를 넘겨줄 수 있다.
부모 컴포넌트
import React from 'react'; import Child from '../pages/Children/Children'; class Parent extends React.Component { constructor() { super(); this.state = { color: 'red' }; } render() { return ( <div> <h1>Parent Component</h1> <Child titleColor={this.state.color}/> </div> ); } } export default State;
titleColor
속성을 생성함titleColor
의 값으로 this.state.color
값을 자식 컴포넌트에게 전달해줌자식 컴포넌트
// Child.js import React from 'react'; class Child extends React.Component { render() { // console.log(this.props); return ( <div> <h1 style={{color : this.props.titleColor}}>Child Component</h1> </div> ); } } export default State;
저기서 props 와 관련된 부분만 따로 떼어서 보자.
<h1 style={{color : this.props.titleColor}}>Child Component</h1>
컴포넌트 내부에서 부모 컴포넌트로부터 전달받은 props를 사용하기 위해서는 state 객체에 접근하는 것과 마찬가지로 props 객체의 특정 키 값을 작성해주면 된다.
물론 event handler 도 전달해줄 수 있다.
부모 컴퍼넌트
import React from 'react'; import Child from '../pages/Children/Children'; class Parent extends React.Component { constructor() { super(); this.state = { color: 'red' }; } handleColor = () => { this.setState({ color: 'blue' }) } render() { return ( <div> <h1>Parent Component</h1> <Child titleColor={this.state.color} changeColor={this.handleColor}/> </div> ); } } export default State;
props의 changeColor 값으로 Parent 함수에서 정의한 handleColor 함수 자체를 넘겨주고 있다.
자식 컴포넌트
import React from 'react'; class Child extends React.Component { render() { // console.log(this.props); return ( <div> <h1 style={{color : this.props.titleColor}}>Child Component</h1> <button onClick={this.props.changeColor}>Click</button> </div> ); } } export default State;
<button>
요소에서 onClick
이벤트가 발생하면서 this.props.changeColor
가 실행된다.handlerColor
를 뜻하기 때문에, 부모 컴포넌트의 handlerColor
함수가 실행된다.color
값을 blue
로 변경하면서 render
함수를 통해 랜더링 되고, <h1>
의 색상이 변경된다.