[esercizio] React Hooks 5

ytwicey·2020년 12월 20일
0

esercizio

목록 보기
6/7

React Hooks 연습하기

5-1. useConfirm

  • useState나 useEffect를 쓰지 않고도 만드는 함수.
  • 사용자가 어떤 동작을 하기 전에 확인하는 함수.

import React, { useState, useEffect } from "react";


const useConfirm = (message = "", callback) => {
  if(typeof callback !== "function"){
    return ;
  }
  
  const confirmed = () => {
  	if(confirm(message)){
    	callback()
    }
  };
  return confirmed;
};

const App1 = () => {
const destroyWorld = () => console.log('it is gone, never come')
const res = useConfirm('Are you sure?', destroyWorld)

return (
	<div>
	<button onClick = {res}> Delete the World </button>
  	</div>
);
};




export default App1;

5-1. 결과물

5-1. 간단 설명

confirm은 window.confirm 이라고 하는 브라우저의 메소드
MDN Window.confirm() 참고

그래서 이 메소드를 이용하여 확인하는 모달창을 띄우는 함수를 생성.
App1 함수 스코프 밖에서 틀과 같은 함수를 만들고, App1 함수 내에서 실사용 할 수 있게 함. 확실히 클래스 컴포넌트일 때보다 간단할 것 같기는 함.





5-2. usePreventLeave

  • 윈도우를 닫으려고 하면, 아직 저장하지 않았다고 알려주는 함수.
  • 마찬가지로 useState, useEffect 없이 작성
import React, { useState, useEffect } from "react";


const usePreventLeave = () => {
  const listener = (event) => {
  event.preventDefault();
  event.returnValue = "";
  }
  
  const enablePrevent = () => {
  	window.addEventListener('beforeunload', listener)
  };
  const disablePrevent = () => {
  	window.removeEventListener('beforeunload', listener)
  };
}

const App1 = () => { 

  const {enablePrevent, disablePrevent } = usePreventLeave()
  
  return (
  <div>
  <button onClick={enablePrevent}>protect</button>
  <button onClick={disablePrevent}>unprotect</button>  
  </div>
  );
  
}

export default App1;

5-2. 결과물

5-2. 간단 설명

여기서 beforeunload 이벤트는 문서와 그 리소스가 언로드 되기 직전에 window에서 발생한다.
참고자료 MDN window: beforeunload event

profile
always 2B#

0개의 댓글