React - Props & Event

Sangho Moon·2020년 9월 12일
1

React

목록 보기
6/9
post-thumbnail

1. Props

  • props : properties(속성)
  • 단어 뜻 그대로 컴포넌트의 속성값입니다.
  • props는 부모 컴포넌트로부터 전달 받은 데이터를 지니고 있는 객체입니다.
  • props를 통해 부모 컴포넌트로부터 자식 컴포넌트에게 state의 상태값, event handler를 넘겨줄 수 있습니다.

2. Props 객체

  • 위에서 props는 부모 컴포넌트로부터 전달 받은 데이터를 지니고 있는 객체라고 했습니다.
  • 클래스형 컴포넌트에서 props, 즉 컴포넌트의 속성을 어떻게 정의하는지 보겠습니다.
// Parent.js

import React from 'react';
import Child from '../pages/Child/Child';

class Parent extends React.Component {
  constructor() {
    super();
    this.state = {
      color: 'red'
    };
  }

  render() {
    return (
      <div>
        <h1>Parent Component</h1>
	<Child />
      </div>
    );
  }
}

export default State;
  • Parent.js: 부모 컴포넌트 입니다.
  • 부모 컴포넌트 안에서 <Child/> 컴포넌트를 import 후 <h1> 태그 아래에 위치해주었습니다.
  • 부모의 state에 있는 데이터를 <Child /> 컴포넌트에게 props를 통해 넘겨보도록 하겠습니다.
// Parent.js

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;
  • 자식 컴포넌트의 props 로 titleColor 속성을 생성해주었습니다.
  • titleColor의 값으로 this.state.color, 즉 부모 컴포넌트의 state 객체 중 color 값을 전달해주었습니다.
  • 이러한 방식으로 props를 통해 부모 컴포넌트 내부의 state 값을 자식 컴포넌트에게 전달할 수 있습니다.
  • <Child /> 컴포넌트 내부에서 전달 받은 props 데이터를 어떻게 사용하는지 확인해보겠습니다.

props 객체

  • state 와 마찬가지로 컴포넌트의 props는 객체입니다.
  • Child.js 내부에서 props 객체가 어떻게 생겼는지 확인해보도록 하겠습니다.
// 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;
  • <Child /> 컴포넌트 내부에 <h1> 태그가 있습니다.
  • 해당 태그의 글자 색상을 부모 컴포넌트의 state 로부터 전달 받은 데이터를 지정해주도록 하겠습니다.
  • render 함수와 return 함수 사이에서 this.props 값을 console.log로 확인합니다.
  • 결과 확인 시 props 객체 안에 부모로 부터 전달받은 데이터가 key-value 형태로 담겨 있는 것을 확인할 수 있습니다.
<h1 style={{color : this.props.titleColor}}>Child Component</h1>

// this : 해당 컴포넌트
// this.props : 해당 컴포넌트의 props 객체
// this.props.titleColor : props 객체의 특정 key(titleColor)값. 즉 "red"
  • 컴포넌트 내부에서 부모 컴포넌트로부터 전달받은 props 데이터를 사용하기 위해서는 state 객체에 접근하는 것과 마찬가지로 props 객체의 특정 키값, 즉 this.props.titleColor 이렇게 작성해주면 됩니다.
  • 다음으로는 props 객체를 통해 부모에서 정의한 event handler를 전달하는 방법을 살펴보겠습니다.

3. Props & event

props를 통한 event handler 전달

// Parent.js

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 객체를 통해 state 데이터 뿐만 아니라 부모에서 정의한 event handler 함수도 넘겨줄 수 있습니다.
  • props의 changeColor 값으로 Parent 함수에서 정의한 handleColor 함수 자체를 넘겨주고 있습니다.
  • <Child /> 컴포넌트에서 어떻게 props로 전달받은 handleColor 함수를 활용하는지 살펴보겠습니다.

// 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>
	<button onClick={this.props.changeColor}>Click</button>
      </div>
    );
  }
}

export default State;
  • <Child /> 컴포넌트 내부에 <button> 태그가 있습니다.
  • 다음의 순서에 따라서 코드가 실행됩니다.
    • <button> 요소에서 onClick 이벤트 발생
    • 이벤트 발생 시 this.props.changeColor 실행
    • props 객체의 changeColor, 즉 부모 컴포넌트로부터 전달받은 handleColor 함수 실행
    • handleColor 함수 실행 시 setState 함수 호출 - state의 color 값을 'blue' 로 변경
    • render 함수 호출
    • <Child /> 컴포넌트에 변경된 state 데이터(this.state.color) 전달
    • this.props.titleColor 를 글자 색상으로 지정하는 <h1> 타이틀 색상 변경
profile
Front-end developer

0개의 댓글