一款更輕便、好用的react輪播組件

日常開發(fā)中,經常遇到要開發(fā)輪播組件的需求,身為一名前端頁面仔,本著拿來主義,當然是去npm上拔拔看有沒有合適的庫。驚奇的發(fā)現react版本的swiper組件庫出奇的少,絕大多數輪播組件庫都依賴于swiper組件。的確swiper組件豐富的api的確能夠滿足日常的開發(fā),但是過于龐大的體積以及在最新版本的一些小bug讓我不得不放棄,所以擼了一個簡單的swiper組件庫去應付日常的開發(fā)。

先放上輪子的地址 react-tiga-swiper,求star。

Install

npm install --save react-tiga-swiper

Usage

import React, { Component } from 'react'

import Swiper,{SwipeRef} from 'react-tiga-swiper'
const swiperData = ["green", "red", "yellow", "black"];

function Example(props){

  const swiperRef = useRef<SwipeRef>(null);
  const [index, setIndex] = useState<any>();

  const swipeTo = () => {
    const swiperInstance = swiperRef.current;
    const currPage: string = index * 1 + '';
    swiperInstance?.swipeTo(parseInt(currPage, 10));
  };

  const prev = () => {
    const swiperInstance = swiperRef.current;
    swiperInstance?.prev();
  };

  const next = () => {
    const swiperInstance = swiperRef.current;
    swiperInstance?.next();
  };

  const onChange = (currPage: number, prevPage: number) => {
    console.log(currPage, prevPage);
  };
  
  return (
    <>
      <div style={{ marginBottom: 20 }}>
        <input
          type="number"
          value={index}
          onChange={(e) => setIndex(e.target.value)}
        />
        <span onClick={swipeTo}>手動跳轉頁面</span>
        <span onClick={prev}>上一頁</span>
        <span onClick={next}>下一頁</span>
      </div>
      <Swiper
        autoPlay={3000}
        style={{ height: "100px"}}
        selectedIndex={0}
        showIndicators={true}
        indicator={null}
        dots={null}
        ref={swiperRef}
        onChange={onChange}
      >
        {swiperData.map((item: string, key) => (
          <div key={key} style={{backgroundColor: item}}>{key + 1}</div>
        ))}
      </Swiper>
    </>
  )
}

API

參數 說明 類型 默認值 備選值
duration 切換動畫持續(xù)時間(ms) number 300
autoPlay 自動切換間隔時間(ms) number 3000
touchable 是否允許滑動 bool true
showIndicators 是否顯示兩側翻頁按鈕 bool true
showDots 是否顯示底部dots bool true
dots 底部dots React.ReactNode null
indicator 兩側翻頁按鈕 React.ReactNode null
style 自定義額外樣式 React.CSSProperties {}
className 自定義額外類名 string ''
onChange 切換時回調函數 (current: number, prev: number): void noop

實例方法

方法名 說明 參數名 參數描述
swipeTo 手動切換輪播圖 index 需要切換的輪播圖索引,從 0 開始
prev 切換至上一張輪播圖
next 切換至下一張輪播圖
?著作權歸作者所有,轉載或內容合作請聯系作者
【社區(qū)內容提示】社區(qū)部分內容疑似由AI輔助生成,瀏覽時請結合常識與多方信息審慎甄別。
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發(fā)布,文章內容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務。

相關閱讀更多精彩內容

友情鏈接更多精彩內容