REACT

REACT_화살표 함수(Arrow Function)

ssmm95 2024. 9. 20. 12:08

<화살표 함수 사용하기>

-ES6 에서 등장한 화살표 함수는 'function' 대신 '=>' 문자열을 사용하며 'return' 문자열을 생략할 수도 있음

따라서 기존 ES5 함수보다 간략하게 선언 할 수 있음. 또 화살표 함수에서는 콜백 함수에서 this를 bind해야 하는 문제도 발생하지 않음

 

- R013_ArrowFunction.js

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;

 

 

- App.js

import React from 'react';
import './App.css'; 
//App.css가 App.js 보다 더 한 단계 상위 폴더에 있다면  
//'./..App.css'

import ArrowFunc from './R013_ArrowFunction.js';

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

export default App;

 

결과

'REACT' 카테고리의 다른 글

REACT_템플릿 문자열  (0) 2024.09.20
REACT_ForEach  (0) 2024.09.20
REACT_Class  (0) 2024.09.20
REACT_ 전개 연산자  (0) 2024.09.20
REACT_ 자식 Component에 node 전달하기  (0) 2024.09.20