react+typescript環境ではswiper custom
20365 ワード
Swiper初期設定
React Typesript環境でのワイパーの使用
ワイパーにカスタムメソッドを設定する
Reactには
refにtypeインタフェースが指定されていないため、エラーが発生します.
Swaperに内蔵されたonSwaperを使用してカスタマイズできます.サンプルコード を使用する前に、 Swaperカスタム例
上記
再生、停止、および(現在のインデックス/合計)表示機能の実装
React Typesript環境でのワイパーの使用
ワイパーにカスタムメソッドを設定する
Reactには
useRef
というHookがあります.refにtypeインタフェースが指定されていないため、エラーが発生します.
Swaperに内蔵されたonSwaperを使用してカスタマイズできます.
import { useState } from 'react';
import SwiperCore from 'swiper';
const Carousel = () => {
const [isSwiper, setIsSwiper] = useState<SwiperCore>();
const settings = useMemo<Swiper>(
() => ({
...
/** onSwiper 메소드를 사용하여 isSwiper에 swiper를 담는다. */
onSwiper: (swiper) => {
setIsSwiper(swiper);
}}),
[]
);
return(
<Swiper {...settings}>
{children}
</Swiper>
)
}
import SwiperCore from 'swiper';
からSWIPERCOREをロードし、ユーザー状態でtypeを<SwiperCore>
に設定します.上記
useState
を使用して、swiperを受信した場合に動作する.再生、停止、および(現在のインデックス/合計)表示機能の実装
Swiper Components
const Carousel = ({
...
children
controller,
autoplay,
}: CarouselProps) => {
/** swiper값을 담음 */
const [isSwiper, setIsSwiper] = useState<SwiperCore>();
/** 자동재생 실행 여부 */
const [isPlay, setIsPlay] = useState(Boolean(autoplay));
/** 현재 슬라이드 인덱스 */
const [currentIndex, setCurrentIndex] = useState(0);
/** children의 갯수를 구함 */
const totalIndex = useMemo(() => Children.count(children), [children]);
const settings = useMemo<Swiper>(
() => ({
...
onSlideChange: (swiper) => setCurrentIndex(swiper.realIndex),
onSwiper: (swiper) => {
setIsSwiper(swiper);
},
}),
[...],
);
// swiper 메소드를 사용하여 자동 재생
const onPlay = useCallback(() => {
isSwiper?.autoplay.start();
setIsPlay(true);
}, [isSwiper?.autoplay]);
// swiper 메소드를 사용하여 정지
const onPause = useCallback(() => {
isSwiper?.autoplay.stop();
setIsPlay(false);
}, [isSwiper?.autoplay]);
return (
<Swiper {...settings}>
{children}
{controller && (
<Controller
currentIndex={currentIndex + 1}
totalIndex={totalIndex}
isPlay={isPlay}
onToggle={() => (isPlay ? onPause() : onPlay())}
/>
)}
</Swiper>
);
};
Controller Components
interface PagingProps {
/** 총 슬라이드 인덱스 */
totalIndex: number;
/** 현재 슬라이드 인덱스 */
currentIndex: number;
/** autoplay 여부 */
isPlay: boolean;
/** 재생 / 정지 클릭 이벤트 */
onToggle: () => void;
}
const Controller = ({
totalIndex,
currentIndex,
onToggle,
}: PagingProps) => {
return (
<div>
<button
type="button"
className="controller"
onClick={onToggle}
>
{isPlay ? (
정지
) : (
재생
)}
</button>
<div className="paging">
<span>
{currentIndex} / {totalIndex}
</span>
</div>
</div>
);
};
export default Controller;
Reference
この問題について(react+typescript環境ではswiper custom), 我々は、より多くの情報をここで見つけました https://velog.io/@yesroad/react-typescript-환경에서-swiper-커스텀テキストは自由に共有またはコピーできます。ただし、このドキュメントのURLは参考URLとして残しておいてください。
Collection and Share based on the CC Protocol