개발/react

arrow function

kwony 2020. 12. 6. 13:59

요즘 트렌드 언어 답게 react에서 사용하는 javascript도 arrow function으로 함수를 줄일 수 있다. 자바에서 사용하는 람다나 swift의 closure 랑 비슷하게 이름없는 함수(anonymous) 를 사용해서 1회성의 함수를 따로 선언하지 않고 삽입해서 쓸 수 있는 기능이다.

 

이 함수들은 모양새는 다르지만 모두 똑같이 제곱값을 리턴하는 함수다.

 

const square1 = function(x) {
    return x * x
};

const square2 = (x) => {
    return x * x;
};

const square3 = (x) => x * x;

 

객체 내에서 함수로 들어갈 때도 동일하게 줄일 수 있다. 

 

const user = {
    name: 'kwony',
    cities: ['pangyo', 'sinchon', 'madrid'],
    printPlacedLived: function() {
        return this.cities.map((city) => {
            return this.name + ' has lived in ' + city + '!';
        });
    },

    printPlacedLived2() {
        return this.cities.map((city) => {
            return this.name + ' has lived in ' + city + '!';
        });
    }
}

 

view 요소의 콜백 함수에도 arrow function을 적용할 수 있다. 아래 코드보면 첫번째 버튼은 arrow function을 적용해서 넣었고 두번째 버튼은 따로 만든 onClickButton 함수를 사용했다. 두개 모두 동일한 역할을 한다.

 

const onClickButton = () => {
    toggle.isVisible = !toggle.isVisible
    render()
}

const render = () => {
    const template = (
        <div>
        <button onClick={() => {
            toggle.isVisible = !toggle.isVisible
            render()
        }}>{toggle.isVisible ? 'hide detail' : 'show detail'}</button>
        <button onClick={onClickButton}>{toggle.isVisible ? 'hide detail' : 'show detail'}</button>

 

간단해보이지만 손에 익으려면 꽤 시간이 걸리니 이것도 놓치지 말고 꼼꼼히 연습해봐야겠다.