TIL.50 Hooks-custom hooks
出版する React公式文書 ノマドコード川の
ユーザがイベントをトリガー(通常はクリックイベント)すると、再確認のウィンドウがポップアップされ、確認時に最初に試みたイベントのhookが実行されます.
ユーザーが「削除」ボタンをクリックします->「本当に削除しますか?」メッセージウィンドウ->メッセージウィンドウで、ユーザーが[うん]ボタン->メッセージウィンドウを閉じて削除を実行
window.confirm、alert、promptは、ブラウザに新しいウィンドウをモードのように表示できます.
選択したタグをアニメーションとして表示する場合は、useFadeInというhookを作成し、パラメータによって表示の時間や方法を表すことができます.
デフォルト設定
useConfirm
ユーザがイベントをトリガー(通常はクリックイベント)すると、再確認のウィンドウがポップアップされ、確認時に最初に試みたイベントのhookが実行されます.
ユーザーが「削除」ボタンをクリックします->「本当に削除しますか?」メッセージウィンドウ->メッセージウィンドウで、ユーザーが[うん]ボタン->メッセージウィンドウを閉じて削除を実行
import React from "react";
const useConfirm = (message = "", onConfirm, onCancel) => {
if (typeof callback !== "function") {
return "Take a function!";
}
// 두 번째 인자로 들어온 함수가 "함수형"인지 확인
const confirmAction = () => {
if (window.confirm(message)) {
onConfirm();
} else {
onCancel()
}
};
// 첫 번째 인자와 두 번째 인자를 사용하여 "확인 메세지창"을 띄움
return confirmAction;
// 결국 useConfirm 이라는 hook 은 값으로 confirmAction()을 리턴한다.
};
const App = () => {
// 자 이제 hook 을 만들었으니 한번 사용해 볼까
// 두 번째 인자에 들어갈 콜백함수를 먼저 만들어 놓고, confirmDelete라는 이름으로 hook을 불러본다.
const deleteWorld = () => console.log("Deleting...");
const abort = () => console.log("Aborted")
const confirmDelete = useConfirm("Are you sure?", deleteWorld, abort);
return (
<div className="App">
<h1>Hello</h1>
<button onClick={confirmDelete}>Delete the world</button>
// (세상을 지워버리시겠습니까..?)
</div>
);
};
export default App;
リファレンス
window.confirm、alert、promptは、ブラウザに新しいウィンドウをモードのように表示できます.
useFadeIn
選択したタグをアニメーションとして表示する場合は、useFadeInというhookを作成し、パラメータによって表示の時間や方法を表すことができます.
デフォルト設定
import React, { useEffect, useRef } from "react";
const useFadeIn = () => {
const element = useRef();
return element;
};
// 1. "useFadeIn"이라는 custom hook을 만든다.
// 2. 사용하고자 하는 view에 만들어 놓은 hook 을 쓰기위해 변수에 할당해 준다.
const App = () => {
const el = useFadeIn()
return (
<div className="App">
<h1 ref={el}>Hello</h1>
</div>
);
};
export default App;
FadeInの追加import React, { useEffect, useRef } from "react";
const useFadeIn = (duration = 1, delay = 0) => {
if (typeof duration !== "number" || typeof delay !== "number") {
return;
}
const element = useRef();
useEffect(() => {
if (element.current) {
const { current } = element;
current.style.transition = `opacity ${duration}s ease-in-out ${delay}s`;
current.style.opacity = 1;
}
}, []);
return { ref: element, style: { opacity: 0 } };
};
// useEffect 를 이용하여 실행시킬 fadeIn 을 설정해준다.
// useRef를 사용하면 current를 통해 선택한 태그의 프로퍼티에 접근가능하며, 객체형태로 설정도 가능하다.
// return 값에도 객체로 할당하여 아래와 같이 변수에 할당하면 {...}(spread operator)형태로 받아서 매번 렌더링을 통해 객체를 전달할 수 있다.
const App = () => {
const fadeInH1 = useFadeIn(3, 2);
const fadeInP = useFadeIn(1, 5);
return (
<div className="App">
<h1 {...fadeInH1}>Hello</h1>
<p {...fadeInP}>hahahaahahahahah</p>
</div>
);
};
export default App;
Reference
この問題について(TIL.50 Hooks-custom hooks), 我々は、より多くの情報をここで見つけました https://velog.io/@h986680/TIL.50-Hooks-custom-hooksテキストは自由に共有またはコピーできます。ただし、このドキュメントのURLは参考URLとして残しておいてください。
Collection and Share based on the CC Protocol