The official website can not set the time of rotation, there is no manual switch case, let’s add a patch to it

Patch to write

The following code

/ * * * *@param carousel carousel ref
 * @param Carousel_autoplay_time User-defined time */
const init_carousel_autoplay = (carousel: any, carousel_autoplay_time: number) = > {
    // Multicast timer
    var carousel_autoplay_timer: any = null
    // Auto play
    const carousel_autoplay = () = > {
        carousel_autoplay_timer = setTimeout(() = > {
            carousel.current.next()
            carousel_autoplay()
        }, carousel_autoplay_time);
    }
    // Clean up timer
    const clear_timeout = (cb: () => void) = > {
        if(carousel_autoplay_timer){
            clearTimeout(carousel_autoplay_timer)
            return
        }
        cb && cb()
    }
    // Reset auto playback
    const reset_aotoplay_timer = () = > {
        / / clean up
        clear_timeout(() = > {
            // Continue the rotation
            carousel_autoplay()
        })
    }
    // Run the following command
    const carousel_prev = () = > {
        reset_aotoplay_timer()
        carousel.current.prev()
    }
    // Take a turn
    const carousel_next = () = > {
        reset_aotoplay_timer()
        carousel.current.next()
    }
    return {
        carousel_autoplay,
        carousel_prev,
        carousel_next,
        clear_timeout,
    }
}

export default init_carousel_autoplay
Copy the code

use

Using code examples

// Set the time for the rotation
const carousel_autoplay_time = 5e3
const { carousel_autoplay, carousel_prev, carousel_next, clear_timeout } = init_carousel_autoplay(carousel, carousel_autoplay_time)
useEffect(() = > {
    // Start multicast
    carousel_autoplay()
    // Leave the cleanup timer
    return clear_timeout
}, [])
Copy the code

There are also two clicks to switch between the previous and the next event. You can use onClick={carousel_prev} directly.

Antd does not have a manual switch example, we can make a div outside, and then make two buttons below it, click on the function using the above patch (using the default, it will conflict with automatic rotation).

Complete code screenshot

other

useEffect(f, [])
Copy the code

UseEffect (f, []) is used because it guarantees that it will only be executed once. Otherwise, every render would be executed once, and countless timers would appear, which would be terrifying. And then I return because I want to destroy the timer

Found by digging friends downstairs cash, autoplaySpeed and autoplay can also be combined. (A bit buggy though)

– the –