REACT

REACT_Callback

ssmm95 2024. 9. 24. 15:19

자바스크립트는 비동기적으로 동작한다

먼저 실행된 작업이 끝나지 않았더라도 다음 작업이 시작될 수 있다

콜백 함수를 아용하면 특정 코드에 순서를 정해 원하는 시점에 실행할 수 있다

 

- R063_CallbackFunc.js

import React, { Component } from 'react';

class R063_CallbackFunc extends Component {
    componentDidMount() {
        this.logPrint(1, function(return1){
            console.log("return1 : " + return1);
            this.logPrint(return1, function(return2){
                console.log("return2 : " + return2);
            })
        }.bind(this))
    }

    logPrint(param, callback) {
        console.log("logPrint param : " + param);
        param += param
        callback(param);
    }

    render() {
        return(
            <h1>Callback Function</h1>
        )
    }
}

export default R063_CallbackFunc;

※  line 7 callback 함수 안에서 this는 line 5의 this와 다르다

그래서 this로 logPrint 함수에 접군해 사용하려고 하면 에러가 발생한다

함수 밖의  this를 함수 안에서도 동일하게 사용하기 위해서 .bind(this)를 함수에 붙여준다

 

- App.js

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

import CallbackFunc from './R063_CallbackFunc'
//import 'bootstrap/dist/css/bootstrap.css'

function App() {
  return (
    <div>
      <h1>Start React 200!</h1>
      <CallbackFunc/>
    </div>
  );
}

export default App;

 

 

결과

'REACT' 카테고리의 다른 글

REACT_Click onClick  (0) 2024.09.25
REACT_Promise Then  (0) 2024.09.24
REACT_AxiosPost  (0) 2024.09.24
REACT_AxiosGet  (1) 2024.09.24
REACT_Fetch Post  (1) 2024.09.24