본문 바로가기

React

화살표 함수 사용하기

728x90

ES6에서 추가된 화살표 함수는 'function'대산 '=>'를 사용하며 'return'을 생략할 수도 있다. 따라서 기존 'function'보다 간략하게 선언이 가능하며, 콜백 함수에서 this를 bind 해야 하는 문제도 발생하지 않는다.

화살표 함수에 대해 알아보기 위해 FunctionCom.js파일을 하나 만들고 App.js에 FunctionCom을 import 시켰다.

1. 기존 Function

기존에 Function은 다음과 같이 사용한다.

import { Component } from "react";

class FunctionCom extends Component{
    constructor(props){
        super(props);
        this.state = {
            arrowFunction: '화살표',
            num: 3
        };
    }

    componentDidMount(){
        Function1(1);
        this.Function2();

        function Function1(num1){
            return console.log("num1 : "+num1);
        }
    }
    Function2(){
        let thisBind = this;
        setTimeout(function(){
            console.log(thisBind.state.arrowFunction);
            console.log(thisBind.state.num);
        })
    }
    
    render(){
        return(
            <h2>화살표 함수</h2>
        )
    }
}

export default FunctionCom;

함수를 정의할 때 기존에 하던 방법대로 함수를 정의하며, 콜백 함수 내부에서는 컴포넌트에 this로 접근할 수 없기 때문에 thisBind 변수에 this를 선언하여 state 변수에 접근해야 한다.

2. 화살표 함수

=>를 이용해 함수를 선언하는 방법은 다음과 같다.

import { Component } from "react";

class FunctionCom extends Component{
    constructor(props){
        super(props);
        this.state = {
            arrowFunction: '화살표',
            num: 3
        };
    }

    componentDidMount(){
        Function1(1);
        this.Function2();
        this.Function3(2);
        this.Function4();

        function Function1(num1){
            return console.log("num1 : "+num1);
        };
    }
    
    Function2(){
        let thisBind = this;
        setTimeout(function(){
            console.log(thisBind.state.arrowFunction);
            console.log(thisBind.state.num);
        })
    }

    Function3 = (num1) => {
        console.log("function3 num1 : " + num1);
    }

    Function4 = () => {
        setTimeout(() => {
            console.log("function4 : "+this.state.arrowFunction);
            console.log("function4 : "+this.state.num);
        })
    }
    
    render(){
        return(
            <h2>화살표 함수</h2>
        )
    }
}

export default FunctionCom;

이와 같이 함수를 선언하여 사용할 수 있으며 콜백 함수 내에서 this를 사용해도 component state에 접근할 수 있어 this를 따로 bind 해주지 않아도 된다.

728x90

'React' 카테고리의 다른 글

React 전개 연산자  (0) 2024.04.12
React 생명주기 함수 '변경'  (0) 2024.03.29
React 생명주기 함수 '생성'  (0) 2024.03.28
React Component 사용하기  (0) 2024.03.27
React 메인 바꿔보기  (0) 2024.03.27