본문 바로가기
FrontEnd/React.js

화살표 함수 사용하기

by J._.cobb 2022. 6. 26.

화살표 함수(Arrow Function)

ES6에서 등장한 화살표 함수는 ‘function’ 대신 ‘⇒’문자열을 사용하며 ‘return’문자열을 생략할 수도 있다. 따라서 기존 ES5 함수보다 가략하게 선언할 수 있다. 또 화살표 함수에서는 콜백 함수에서 this를 bind해야 하는 문제도 발생하지 않는다.

 

예제코드

App.js

import React from 'react';
import './App.css';
import ArrowFunc from './R013_ArrowFunction';

function App() {
  return (
    <div>
      <h1>Start React 200!</h1>
      <p>css 적용하기</p>
      <ArrowFunc/>
    </div>
  );
}

export default App;

R013_ArrowFunction

import React, { Component } from "react";

class R013_ArrowFunction extends Component {

  constructor(props){
    super(props);
    this.state = {
      arrowFunc: 'React200',
      num: 3
    };
  }

  componentDidMount() {
    Function1(1);
    this.Function2(1,1);
    this.Function3(1,3);
    this.Function4();
    this.Function5(0,2,3);

    function Function1(num1){
      return console.log(num1+'. ES5 Function');
    }
  }

  Function2 = (num1, num2) => {
    let num3 = num1 +num2;
    console.log(num3+'. Arrow Function : '+this.state.arrowFunc);
  }

  Function3() {
    var this_bind = this;
    setTimeout(function() {
      console.log(this_bind.state.num+'. Es5 Callback Function noBind : ');
      console.log(this.state.arrowFunc);
    }, 100);
  }

  Function4() {
    setTimeout(function() {
      console.log('4. Es5 Callback Function Bind : '+this.state.arrowFunc);
  }.bind(this),100);
  }

  Function5 = (num1, num2, num3) => {
    const num4 = num1 + num2 + num3;
    setTimeout(() => {
      console.log(num4+'. Arrow Callback Function : '+this.state.arrowFunc);
    }, 100);
  }

  render() {
    return (
      <h2>[THIS IS ArrowFunction]</h2>
    )
  }
}

export default R013_ArrowFunction;

코드 해설

  • Function 1~5까지의 함수를 순서대로 호출한다.
  • 함수를 호출할 때 전달받은 num1이라는 변수를 함수 내부에서 사용할 수 있다.
  • 함수를 ‘function’문자열 대신 ‘⇒’로 선언했다. 함수 내에서 사용하는 this는 R013_ArrowFunction 컴포넌트인데, this로 컴포넌트의 state 변수에 접근해 사용할 수 있다.
  • 콜백 함수 내부에서는 컴포넌트에 this로 접근할 수 없기 때문에 접근할 수 있는 변수에 this를 백업한다. 백업된 변수인 this_bind를 이용해 컴포넌트의 state 변수에 접근할 수 있다.
  • 콜백 함수 내부에서 this는 window 객체이기 때문에 this로 state 변수에 접근하면 undefined에러가 발생한다.
  • 콜백 함수에 함수 밖에 this를 bind해주면, this를 컴포넌트로 사용할 수 있다.
  • 화살표 함수에서는 this를 bind해주지 않아도 this를 컴포넌트로 사용해 state 변수에 접근할 수 있다.

결과화면

'FrontEnd > React.js' 카테고리의 다른 글

map()함수 사용하기  (0) 2022.06.27
forEach() 함수 사용하기  (0) 2022.06.26
class 사용하기  (0) 2022.06.26
전개 연산자 사용하기  (0) 2022.06.26
React의 생명주기-변경  (0) 2022.06.23