라이브러리를 React 후크로 래핑
6446 단어 hooktypescriptreactjavascript
이 기사에서는 스 와이프 감지 라이브러리를 React 후크로 래핑합니다.
💡 이 기사는 내부적으로 사용되는 스와이프 감지 라이브러리의 공개 인터페이스에 대해 잘 알고 있음을 암시합니다. 시리즈의 첫 번째 기사를 읽지 않았다면 이 기사의 내용을 따라가는 것만으로도 충분할 것입니다.
작동 방식
재사용 가능한 React 후크에서 기본 라이브러리의 스와이프 감지 기능을 래핑하려고 합니다. 후크 명명 규칙을 따르는 것이 중요하므로 하나
useSwipe를 호출해 보겠습니다. 소비자 구성 요소에서 후크가 사용되는 방식은 다음과 같습니다.const swipeElement = useSwipe({
onSwipeEnd: (event: SwipeEvent) => {
console.log(`SwipeEnd direction: ${event.direction} and distance: ${event.distance}`);
}
});
return <div ref={swipeElement}>Swipe me!</div>
완벽한 솔루션
래퍼 후크는 매우 간결합니다.
import { createSwipeSubscription, SwipeSubscriptionConfig } from 'ag-swipe-core';
import { RefCallback, useCallback } from 'react';
import { Subscription } from 'rxjs';
export const useSwipe = (config: Pick<SwipeSubscriptionConfig, 'onSwipeMove' | 'onSwipeEnd'>): RefCallback<HTMLElement> => {
let swipeSubscription: Subscription | undefined;
return useCallback((domElement: HTMLElement) => {
if (domElement) {
swipeSubscription = createSwipeSubscription({
domElement,
...config
});
} else {
swipeSubscription?.unsubscribe?.();
}
}, []);
}
후크에서 원하는 것은 다음과 같습니다.
첫 번째 의도는
useRef 및 useEffect 후크의 조합을 사용하는 것일 수 있지만 실제로 필요한 것은 ref 및 useCallback의 조합입니다.... the callback ref will be called only when the component mounts and unmounts
더 나은 핏을 요구할 수 없습니다.
domElement에서 오는 ref 매개변수 값이 사실이면, 즉 구성 요소가 마운트된 경우 제공된 createSwipeSubscription 및/또는 onSwipeMove 처리기로 onSwipeEnd를 호출합니다. 값이 잘못된 경우, 즉 구성 요소가 마운트 해제된 경우 swipeSubscription 참조를 사용하여 구독을 취소합니다.ref 및 useCallback가 함께 작동하는 방법에 대한 자세한 내용은 this section in React documentation을 참조하십시오.마무리
this link의 GitHub에서 전체 라이브러리 코드를 찾을 수 있습니다.
그리고 this link에 의한
npm 패키지.그거였다! 우리는 17줄의 코드로 스와이프 감지 라이브러리를 위한 간단한 React 후크 래퍼를 구축했습니다.
이 기사는 짧은 시리즈를 완료합니다. 읽어주셔서 감사합니다.
Reference
이 문제에 관하여(라이브러리를 React 후크로 래핑), 우리는 이곳에서 더 많은 자료를 발견하고 링크를 클릭하여 보았다 https://dev.to/this-is-learning/wrapping-library-in-a-react-hook-193e텍스트를 자유롭게 공유하거나 복사할 수 있습니다.하지만 이 문서의 URL은 참조 URL로 남겨 두십시오.
우수한 개발자 콘텐츠 발견에 전념
(Collection and Share based on the CC Protocol.)