react/antd -- 让antd的跑马灯支持自轮播的时间

5,079 阅读1分钟

官网那边不能设置轮播的时间,也没有手动切换案例,下面我们给他添加一个补丁吧

补丁编写

代码如下

/**
 * 
 * @param carousel carousel ref
 * @param carousel_autoplay_time 自定义时间
 */
const init_carousel_autoplay = (carousel: any, carousel_autoplay_time: number) => {
    // 轮播定时器
    var carousel_autoplay_timer: any = null
    // 自动播放
    const carousel_autoplay = () => {
        carousel_autoplay_timer = setTimeout(() => {
            carousel.current.next()
            carousel_autoplay()
        }, carousel_autoplay_time);
    }
    // 清理定时器
    const clear_timeout = (cb: () => void) => {
        if(carousel_autoplay_timer){
            clearTimeout(carousel_autoplay_timer)
            return
        }
        cb && cb()
    }
    // 重置自动播放
    const reset_aotoplay_timer = () => {
        // 清理
        clear_timeout(() => {
            // 继续轮播
            carousel_autoplay()
        })
    }
    // 轮播上一个
    const carousel_prev = () => {
        reset_aotoplay_timer()
        carousel.current.prev()
    }
    // 轮播下一个
    const carousel_next = () => {
        reset_aotoplay_timer()
        carousel.current.next()
    }
    return {
        carousel_autoplay,
        carousel_prev,
        carousel_next,
        clear_timeout,
    }
}

export default init_carousel_autoplay

使用

使用代码示例

// 定时轮播时间
const carousel_autoplay_time = 5e3
const { carousel_autoplay, carousel_prev, carousel_next, clear_timeout } = init_carousel_autoplay(carousel, carousel_autoplay_time)
useEffect(() => {
    // 启动轮播
    carousel_autoplay()
    // 离开清理定时器
    return clear_timeout
}, [])

这里还有两个点击切换上一个和下一个的事件,可直接使用 onClick={carousel_prev}

antd没有手动切换的例子,我们可以在外面包一个div,然后下面弄两个按钮就可以了,点击用上面补丁的函数(使用默认的话,会和自动轮播冲突哦)

完整代码截图

其他

useEffect(f, [])

之所以要用useEffect(f, []), 是因为这样保证了它只会执行一次。不然每一次渲染都执行一次,无数个定时器出现,那也太恐怖了。 然后之所以要return,是因为要销毁定时器

发现
经楼下掘友提现,autoplaySpeedautoplay配合也是可以的哈。(虽然有点bug)

--完--